2

如何获取下面数组中第一个索引中的所有单词并获取下一个索引???数组 2 D 中的最后一个单词,.. 示例:

$arr = array( 
  array( 
    '3'=>'repsol kawasaki honda ktm', 
    '4'=>'kawasaki honda ktm bmw', 
    '5'=>'honda ktm bmw ducati', 
    '6'=>'ktm bmw ducati yamaha'
  ) , 
  array( 
    '13'=>'lamborghi ferarri mercedes hyundai', 
    '14'=>'ferarri mercedes hyundai toyota',
    '15'=>'mercedes hyundai toyota nissan',
    '16'=>'hyundai toyota nissan renault'
  ), 
);

我想要这样的产量:

   Array ( 
     [0] => Array (
       [0] => repsol kawasaki honda ktm 
       [1] => bmw 
       [2] => ducati
       [3] => yamaha 
      ) 
     [1] => Array ( 
       [13] => lamborghi ferarri mercedes hyundai 
       [14] => toyota 
       [15] => nissan  
       [16] => renault 
       ) 
   )
4

1 回答 1

1

这应该做你想要的......

function parseArray( &$arr ){
  $out = array();
  $keys = array_keys( $arr );
  $out[ $keys[0] ] = $arr[$keys[0]];
  unset($arr[$keys[0]]);
  foreach( $arr as $key => $val ){
    $out[ $key ] = array_pop( explode(' ', $val ) );
  }
  $arr = $out;
}

然后array_walk像这样将函数应用于每个内部数组

$data = array(
  array(
    '3'=>'repsol kawasaki honda ktm', 
    '4'=>'kawasaki honda ktm bmw',   
    '5'=>'honda ktm bmw ducati', 
    '6'=>'ktm bmw ducati yamaha'
  ),
  array(
    '13'=>'lamborghi ferarri mercedes hyundai',
    '14'=>'ferarri mercedes hyundai toyota',
    '15'=>'mercedes hyundai toyota nissan',
    '16'=>'hyundai toyota nissan renault'
  )
);

echo "Before:\n";
print_r($data);
// Walk our array
array_walk( $data, 'parseArray');

echo "After\n";
print_r($data);

输出

Before:
Array
(
    [0] => Array
        (
            [3] => repsol kawasaki honda ktm
            [4] => kawasaki honda ktm bmw
            [5] => honda ktm bmw ducati
            [6] => ktm bmw ducati yamaha
        )

    [1] => Array
        (
            [13] => lamborghi ferarri mercedes hyundai
            [14] => ferarri mercedes hyundai toyota
            [15] => mercedes hyundai toyota nissan
            [16] => hyundai toyota nissan renault
        )

)

After:    
Array
(
    [0] => Array
        (
            [3] => repsol kawasaki honda ktm
            [4] => bmw
            [5] => ducati
            [6] => yamaha
        )

    [1] => Array
        (
            [13] => lamborghi ferarri mercedes hyundai
            [14] => toyota
            [15] => nissan
            [16] => renault
        )

)
于 2012-11-03T08:09:24.387 回答