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

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

提交回复
热议问题