//ads:
?>
PHP rotate matrix counter-clockwise
PHP Snippet 1:
$b = call_user_func_array(
'array_map',
array(-1 => null) + array_map('array_reverse', $a)
);
PHP Snippet 2:
$a = [[1,2,3,4],[1,2,3,4],[3,4,5,6],[3,4,5,6]];
var_export(array_reverse(array_map(null, ...$a)));
PHP Snippet 3:
$result = [];
foreach ($array as $row) {
foreach ($row as $i => $v) {
$result[$i][] = $v;
}
}
var_export(array_reverse($result));
PHP Snippet 4:
$result = [];
foreach ($array as $row) {
foreach (array_reverse($row) as $i => $v) {
$result[$i][] = $v;
}
}
var_export($result);
PHP Snippet 5:
$a = array(array(1,2,3,4),array(5,6,7,8),array(9,0,1,2),array(3,4,5,6));
$b = $a; //result
$clockwise = false; // toggle for clockwise / counter-clockwise
$rows = count($a);
$columns = ($rows > 0) ? count($a[0]) : 0;
for ($y = 0; $y < $rows; $y++) {
for ($x = 0; $x < $columns; $x++) {
$newX = $clockwise ? $y : ($rows - 1) - $y;
$newY = $clockwise ? ($columns - 1) - $x : $x;
$b[$newX][$newY] = $a[$x][$y];
}
}
PHP Snippet 6:
$m = array();
$m[0] = array('a', 'b', 'c');
$m[1] = array('d', 'e', 'f');
$m[2] = array('g', 'h', 'i');
$newMatrix = array();
function rotateMatrix($m, $i = 0, &$newMatrix)
{
foreach ($m as $chunk) {
$newChunk[] = $chunk[$i];
}
$newMatrix[] = array_reverse($newChunk);
$i++;
if ($i < count($m)) {
rotateMatrix($m, $i, $newMatrix);
}
}
rotateMatrix($m, 0, $newMatrix);
echo '<pre>';
var_dump($newMatrix);
echo '<pre>';