How can I rotate a 2d array in php 90 degrees

I want to rotate the matrix 90 degrees clockwise. This boils down to the fact that the first input column introduces the first output line, the second input column of the second output line, and the third input column of the third output line. Note that the bottom of the column = the beginning of the row due to a 90 degree rotation.

For instance:

$matrix= [[1, 2, 3] [4, 5, 6], [7, 8, 9]]; rotate90degrees($matrix)= [[7, 4, 1], [8, 5, 2], [9, 6, 3]] 

I know that I first transfer the matrix, and then change the columns to rotate the matrix 90 degrees. How can this be applied to php?

+6
source share
3 answers

php does not have concepts like transpose for a matrix without adding any linear algebra library. you can do this initially by using a matrix and replacing some indices

 <?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 
+2
source

I showed you how to transpose an array in response to the previous question , to rotate it 90 degrees, use this transposed logic, and then change 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

+6
source

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 smart than @ mark-baker. Perhaps more clear.

+2
source

Source: https://habr.com/ru/post/986691/


All Articles