Friday, June 17, 2011

Transpose 2D array in PHP

Transposing means swapping columns and rows so that columns become rows and vice versa. When searching for a nice function which I could copy/paste to my code I have found the following comment to the array_map() function (http://de2.php.net/manual/en/function.array-map.php#86743):

To transpose rectangular two-dimension array, use the following code:
array_unshift($array, null);$array = call_user_func_array("array_map", $array);
If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:$array = array_reverse($array);
Here is example:
$a = array(
  array(
  array(123),
  array(
  array(456));array_unshift($anull);$a call_user_func_array("array_map"$a);print_r($a);?>
Output:
Array( [0] => Array        (            [0] => 1            [1] => 4        )
    [1] => Array        (            [0] => 2            [1] => 5        )
    [2] => Array        (            [0] => 3            [1] => 6        )
)
These two lines has puzzled me for some time. I don't like being puzzled for long, so, after unpuzzling, it appears rather simple. The magic trick is in multiple arguments to the array_map() function. Minimal example:

$a = array_map(NULL, array(1, 'a'), array(2, 'b'));

makes:

array(
  array(1, 2),
  array('a', 'b')
);

This way each element of the first parameter array (1, 'a') gets combined with each element of the second parameter.

The NULL callback function is a short-cut of:

function ($a, $b) {
  return array($a, $b);
}

Anyway, I find this little hack fascinating.

No comments: