Skip to content

Instantly share code, notes, and snippets.

@edulan
Created August 10, 2011 12:08
Show Gist options
  • Save edulan/1136654 to your computer and use it in GitHub Desktop.
Save edulan/1136654 to your computer and use it in GitHub Desktop.
PHP matrix transpose using a functional approach
<?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
@hoseinz3
Copy link

hoseinz3 commented Dec 6, 2017

@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