Created
August 10, 2011 12:08
-
-
Save edulan/1136654 to your computer and use it in GitHub Desktop.
PHP matrix transpose using a functional approach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$matrix = array( | |
array('a', 1, 2), | |
array('b', 3, 4), | |
array('c', 5, 6), | |
array('d', 7, 8) | |
); | |
$transpose = array_reduce( | |
$matrix, | |
function ($acum, $row) { | |
array_walk( | |
$row, | |
function($column, $index, $acum) { | |
$acum[$index][] = $column; | |
}, | |
&$acum | |
); | |
return $acum; | |
}, | |
array() | |
); | |
print_r($transpose); | |
// Output: | |
// ------- | |
// a b c d | |
// 1 3 5 7 | |
// 2 4 6 8 | |
?> | |
// Taste it! | |
// php -f transpose.php |
@sangharsha, PHP 5.6:
$matrix = [
['a', 1, 2],
['b', 3, 4],
['c', 5, 6],
['d', 7, 8]
];
print_r(array_map(NULL, ...$matrix));
@qRoC can you explain how your beautiful trick works?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
any workaround to make this work with newer version of PHP, specially when the pointers are not allowed anymore?