How can I rotate a 2d array in php by 90 degrees
Another reliable option:
function rotateMatrix90( $matrix )
{
$matrix = array_values( $matrix );
$matrix90 = array();
// make each new row = reversed old column
foreach( array_keys( $matrix[0] ) as $column ){
$matrix90[] = array_reverse( array_column( $matrix, $column ) );
}
return $matrix90;
}
Less clever than @mark-baker's by far. Maybe more clear.
I showed you how to transpose an array in answer to a previous question, to rotate 90 degrees, use that transpose logic, and then reverse the order of the values in each row in turn:
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
array_unshift($matrix, null);
$matrix = call_user_func_array('array_map', $matrix);
$matrix = array_map('array_reverse', $matrix);
var_dump($matrix);
Demo
php doesn't have concepts like "transpose" for a matrix without adding some sort of linear algebra library. you can do it natively by eaching through the matrix and swapping some indexes
<?php
function rotate90($mat) {
$height = count($mat);
$width = count($mat[0]);
$mat90 = array();
for ($i = 0; $i < $width; $i++) {
for ($j = 0; $j < $height; $j++) {
$mat90[$height - $i - 1][$j] = $mat[$height - $j - 1][$i];
}
}
return $mat90;
}
$mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
print_r($mat);
//123
//456
//789
print_r(rotate90($mat));
//741
//852
//963
$mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["a", "b", "c"]];
print_r($mat);
//123
//456
//789
//abc
print_r(rotate90($mat));
//a741
//b852
//c963