The purpose of this code is to change each column to a row, and assign keys to each value for the new array according to the old array. I would like to know if there're other ways to optimize it.
<?php
$arr = [
'name' => ['a', 'b', 'c'],
'age' => [ 2 , 1 , 3 ]
];
$result = [];
$keys = array_keys($arr);
foreach($arr[$keys[0]] as $index => $temp) {
$data = [];
foreach($keys as $i => $key) {
$data[$key] = $arr[$key][$index];
}
$result[] = $data;
}
print_r($result);
Which gives:
$result = [
['name' => 'a', 'age' => 2],
['name' => 'b', 'age' => 1],
['name' => 'c', 'age' => 3],
];