这不应该让我感到困惑,但我希望能够解决这个问题:
array:3 [▼
"subject" => array:2 [▼
0 => "math"
1 => "english"
]
"grade" => array:2 [▼
0 => "a"
1 => "b"
]
"received" => array:2 [▼
0 => "2017"
1 => "2016"
]
]
进入这个:
array:2 [▼
"0" => array:3 [▼
"subject" => "math"
"grade" => "a"
"received" => "2017"
]
"1" => array:3 [▼
"subject" => "english"
"grade" => "b"
"received" => "2016"
]
]
尝试以几种不同的方式循环,但似乎永远不会得到我想要的结果,任何帮助都会非常感激!
答案 0 :(得分:4)
$keys = array_keys($array);
$result = array_map(
function (...$values) use ($keys) { return array_combine($keys, $values); },
...array_values($array)
);
本质上是这个,但重复性较低:
array_map(
function ($subject, $grade, $received) {
return [
'subject' => $subject,
'grade' => $grade,
'received' => $received
];
},
$array['subject'],
$array['grade'],
$array['received']
)
答案 1 :(得分:1)
简单版本:
$arr1 = array(...);
$arr2 = array();
foreach ($arr1 as $k => $v) {
foreach ($v as $x => $y) {
$arr2[$x][$k] = $y;
}
}
但是你应该添加条件,如果数组元素不存在,创建它,或者你可能会得到错误,具体取决于你的PHP配置。