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.)
function transpose($array, &$out, $indices = array()) { if (is_array($array)) { foreach ($array as $key => $val) { //push onto the stack of indices $temp = $indices; $temp[] = $key; transpose($val, $out, $temp); } } else { //go through the stack in reverse - make the new array $ref = &$out; foreach (array_reverse($ ...
A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation.
The transpose of a matrix is found by interchanging its rows into columns or columns into rows. The transpose of the matrix is denoted by using the letter “T” in the superscript of the given matrix. For example, if “A” is the given matrix, then the transpose of the matrix is represented by A' or AT.
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); }
With 2 loops.
function flipDiagonally($arr) { $out = array(); foreach ($arr as $key => $subarr) { foreach ($subarr as $subkey => $subvalue) { $out[$subkey][$key] = $subvalue; } } return $out; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With