Transposing multidimensional arrays in PHP

Calvin picture Calvin · Apr 28, 2009 · Viewed 45.2k times · Source

How would you flip 90 degrees (transpose) a multidimensional array in PHP? For example:

// Start with this array
$foo = array(
    'a' => array(
       1 => 'a1',
       2 => 'a2',
       3 => 'a3' 
    ),
    'b' => array(
       1 => 'b1',
       2 => 'b2',
       3 => 'b3' 
    ),
    'c' => array(
       1 => 'c1',
       2 => 'c2',
       3 => 'c3' 
    )
);

$bar = flipDiagonally($foo); // Mystery function
var_dump($bar[2]);

// Desired output:
array(3) {
  ["a"]=>
  string(2) "a2"
  ["b"]=>
  string(2) "b2"
  ["c"]=>
  string(2) "c2"
}

How would you implement flipDiagonally()?

Edit: this is not homework. I just want to see if any SOers have a more creative solution than the most obvious route. But since a few people have complained about this problem being too easy, what about a more general solution that works with an nth dimension array?

i.e. How would you write a function so that:

$foo[j][k][...][x][y][z] = $bar[z][k][...][x][y][j]

?(ps. I don't think 12 nested for loops is the best solution in this case.)

Answer

Codler picture Codler · Aug 6, 2010
function transpose($array) {
    array_unshift($array, null);
    return call_user_func_array('array_map', $array);
}

Or if you're using PHP 5.6 or later:

function transpose($array) {
    return array_map(null, ...$array);
}