Transposing a PHP associative array 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.

&lt;?php

$arr = [
    'name' =&gt; ['a', 'b', 'c'],
    'age'  =&gt; [ 2 ,  1 ,  3 ]
];

$result = [];
$keys   = array_keys($arr);
foreach($arr[$keys[0]] as $index =&gt; $temp) {
    $data = [];
    foreach($keys as $i =&gt; $key) {
        $data[$key] = $arr[$key][$index];
    }
    $result[] = $data;
}

print_r($result);


Which gives:

$result = [
    ['name' =&gt; 'a', 'age' =&gt; 2],
    ['name' =&gt; 'b', 'age' =&gt; 1],
    ['name' =&gt; 'c', 'age' =&gt; 3],
];
There isn't really any great performance improvement to be made here in my opinion.  You original structure is going to require nested loop approach to generate your desired structure regardless.

My only suggestion would be building an array of objects in your result rather than an array of associative arrays, as I think what you have shown in your example is more meaningful as objects (i.e. items that have a set of properties) vs. as an associative array (which I typically like to use more for hashmap type of use cases).