PHP - how to flip the rows and columns of a 2D array

后端 未结 10 1397
猫巷女王i
猫巷女王i 2020-12-06 02:24

Normally I\'d be asking how to turn something like this:

1      2        3
4      5        6
7      8        9
10    11       12

Into this:

10条回答
  •  悲哀的现实
    2020-12-06 03:12

    I had to write this one to inverse an array of name indexed arrays. It's very useful for printing php array as as html table, as it even fills missing elements with nulls so the number of is same for all rows of html table.

      /**
      * Inverses a two dimentional array.
      * The second dimention can be name indexed arrays, that would be preserved.
      * This function is very useful, for example, to print out an html table
      * from a php array.
      * It returns a proper matrix with missing valus filled with null.
      *
      * @param type $arr input 2d array where second dimention can be. name indexed
      * arrays.
      * @return 2d_array returns a proper inverted matrix with missing values filled with
      * nulls
      * @author Nikolay Kitsul
      */
     public static function array_2D_inverse($arr) {
         $out = array();
         $ridx = 0;
         foreach ($arr as $row) {
             foreach ($row as $colidx => $val) {
                 while ($ridx > count($out[$colidx]))
                     $out[$colidx][] = null;
                 $out[$colidx][] = $val;
             }
             $ridx++;
         }
         $max_width = 0; 
         foreach($out as $v)
              $max_width = ($max_width < count($v)) ? count($v) : $max_width;
         foreach($out as $k => $v){
             while(count($out[$k]) < $max_width)
                 $out[$k][] = null;
         }
         return $out;
     }
    

提交回复
热议问题