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

后端 未结 10 1372
猫巷女王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:11

    falvarez, the ZOrderToNOrder function does not work correctly when one or more columns have got one more element that other columns (other > 1).

    i think this code fix it:

    public static function ZOrderToNOrder($array, $columns) {
        $numElements = count($array);
    
        $maxRows = array();
        for ($i = 0; $i < $columns; $i++) {
            $maxRows[$i] = intval(ceil(($numElements - $i) / $columns));
        }
    
        $newArray = array();
    
        $rowCounter = 0;
        $colCounter = 0;
        foreach ($array as $element) {
            $newArray[$rowCounter][$colCounter] = $element;
            $rowCounter++;
            if ($rowCounter === $maxRows[$colCounter]) {
                $rowCounter = 0;
                $colCounter++;
            }
        }
    
        return self::arrayFlatten($newArray);
    }
    

    Regards,

    Armando

    0 讨论(0)
  • 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 <b>name indexed</b> 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. <b>name indexed</b>
      * 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;
     }
    
    0 讨论(0)
  • 2020-12-06 03:14

    I have developed this code, based partially in a solution found here to flatten multidimensional arrays.

    Hope it helps!

    /**
     *
     * http://stackoverflow.com/questions/2289475/converting-php-array-of-arrays-into-single-array
     * @param array $array
     * @return array
     */
    function arrayFlatten(array $array)
    {
        $flatten = array();
        array_walk_recursive($array, function($value) use(&$flatten)
        {
            $flatten[] = $value;
        });
    
        return $flatten;
    }
    
    /**
     *
     *  Reorders an array to put the results ordered as a "N", instead of a "Z"  
     *
     * @static
     * @param $array Array to be ordered
     * @param $columns Number of columns of the "N"
     * @return void
     */
    function ZOrderToNOrder($array, $columns)
    {
        $maxRows = ceil(count($array) / $columns);
        $newArray = array();
        $colCounter = 0;
        $rowCounter = 0;
        foreach ($array as $element)
        {
            $newArray[$rowCounter][] = $element;
            $rowCounter++;
            if ($rowCounter == $maxRows)
            {
                $colCounter++;
                $rowCounter = 0;
            }
        }
    
        return arrayFlatten($newArray);
    }
    
    0 讨论(0)
  • 2020-12-06 03:15
    $output_array = [];
    foreach ($input_array as $column_id => $rows) {
        foreach ($rows as $row_id => $value) {
            if (!array_key_exists($row_id, $output_array)) {
                $output_array[$row_id] = [];
            }
            $output_array[$row_id][$column_id] = $value;
        }
    }
    

    is my usual solution, this just ensures that row id exists as a valid index before writing to it. This will preserve all keys, and switch rows and columns from $input_array into $output_array

    0 讨论(0)
提交回复
热议问题