如何获取下面数组中第一个索引中的所有单词和下一个索引获取??? 数组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
)
)
答案 0 :(得分: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
)
)