是否有内置的PHP函数可以实现以下效果?我不知道如何描述这个问题,但我觉得我以前在某个地方看到过一个解决方案:
如何更改:
array(
['name'] => array(
[0] => 'Pat',
[1] => 'Sam',
[2] => 'Chris'
),
['score'] => array (
[0] => '100',
[1] => '95',
[2] => '109'
),
['color'] => array (
[0] => 'blue',
[1] => 'red',
[3] => 'green'
)
)
到此:
array(
[0] => array(
['name'] => 'Pat',
['score'] => '100',
['color'] => 'blue'
),
[1] => array(
['name'] => 'Sam',
['score'] => '95',
['color'] => 'red'
),
[2] => array(
['name'] => 'Chris',
['score'] => '109',
['color'] => 'green'
)
)
如果没有,递归函数是否是解决此问题的正确方法?
答案 0 :(得分:0)
我不知道任何内置函数,但有几个循环可以做到这一点。
$ar = array(
'name' => array(
0 => 'Pat',
1 => 'Sam',
2 => 'Chris'
),
'score' => array (
0 => '100',
1 => '95',
2 => '109'
),
'color' => array (
0 => 'blue',
1 => 'red',
3 => 'green'
),
);
$new_ar = array();
foreach($ar as $key => $val) {
foreach($val as $key2 => $val2) {
$new_ar[$key2][$key] = $val2;
}
}
print_r($new_ar);
答案 1 :(得分:0)
$arr = array(
'name'=> array('Pat', 'Sam', 'Chris'),
'score'=> array ( '100', '95','109'),
'color'=> array ('blue', 'red', 'green')
);
array_unshift($arr, null);
echo "<pre>"; print_r(call_user_func_array('array_map', $arr));
答案 2 :(得分:0)
试试这肯定会帮助你
<?php
$old = array(
'name' => array('Pat', 'Sam','Chris'),
'score' => array('100', '95','109'),
'color' => array('blue', 'red','green'),
);
foreach($old as $key => $value){
$i = 0;
foreach($value as $sub_key => $sub_value){
$new[$i][$key] = $sub_value;
$i++;
}
}
print_r($new);
?>
输出:
Array
(
[0] => Array
(
[name] => Pat
[score] => 100
[color] => blue
)
[1] => Array
(
[name] => Sam
[score] => 95
[color] => red
)
[2] => Array
(
[name] => Chris
[score] => 109
[color] => green
)
)
答案 3 :(得分:0)
您的第一个数组是一个二维数组,即一个矩阵,从数学的角度来看,您想要的结果是转置矩阵(但保留了键),因此您可以查看here的某些答案关于在PHP中转置矩阵。我还根据你提到的问题调整了上述问题的答案:
$arr = array(
'name' => array('Pat', 'Sam', 'Chris'),
'score' => array ('100', '95', '109'),
'color' => array ('blue', 'red', 'green')
);
$arr_keys = array_keys($arr);
array_unshift($arr, function(){
return array_combine($GLOBALS['arr_keys'], func_get_args());
});
$result = call_user_func_array('array_map', $arr);
print_r($result);