My snippets will not outperform yours because function calls will come with more overhead, but I think I'll post them anyhow to show some flexible alternatives.
If you would like to avoid the nested loop structure, yet have a dynamic method that will permit key name changes and increases in "rows" and "columns" with just one foreach loop, then array_column()
and array_combine()
are useful:
Code: (Demo)
$arr = [
'name' => ['a', 'b', 'c', 'd'],
'age' => [ 2 , 1 , 3 , 4 ],
'shoe' => [11 , 9 , 8 , 10 ],
'kids' => [ 1 , 0 , 2 , 3 ]
];
$keys = array_keys($arr);
foreach ($arr[$keys[0]] as $k => $v) { // only iterate first "row"
$result[] = array_combine($keys, array_column($arr, $k)); // store each "column" as an associative "row"
}
var_export($result);
Output:
array (
0 =>
array (
'name' => 'a',
'age' => 2,
'shoe' => 11,
'kids' => 1,
),
1 =>
array (
'name' => 'b',
'age' => 1,
'shoe' => 9,
'kids' => 0,
),
2 =>
array (
'name' => 'c',
'age' => 3,
'shoe' => 8,
'kids' => 2,
),
3 =>
array (
'name' => 'd',
'age' => 4,
'shoe' => 10,
'kids' => 3,
),
)
If you might have missing values in your subarrays, then using array_map()
's transposing technique can autofill elements with null
elements. This will be more expensive, but the benefit is in the potential data stability.
Code: (Demo)
$arr = [
'name' => ['a', 'b', 'c'],
'age' => [ 2 , 1 , 3 , 4 ],
'shoe' => [11 , 9 ],
'kids' => [ 1 , 0 , 2 ]
];
$keys = array_keys($arr);
$transposed = array_map(null, ...array_values($arr));
foreach ($transposed as &$subarray) {
$subarray = array_combine($keys, $subarray);
}
var_export($transposed);
Output:
array (
0 =>
array (
'name' => 'a',
'age' => 2,
'shoe' => 11,
'kids' => 1,
),
1 =>
array (
'name' => 'b',
'age' => 1,
'shoe' => 9,
'kids' => 0,
),
2 =>
array (
'name' => 'c',
'age' => 3,
'shoe' => NULL,
'kids' => 2,
),
3 =>
array (
'name' => NULL,
'age' => 4,
'shoe' => NULL,
'kids' => NULL,
),
)