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

后端 未结 10 1386
猫巷女王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 02:56

    Just walk the array in the correct order. Assuming you have relatively small arrays, the easiest solution is just to create a brand new array during that walk.

    A solution will be of the form:

    $rows = count($arr);
    $cols = count($arr[0]); // assumes non empty matrix
    $ridx = 0;
    $cidx = 0;
    
    $out = array();
    
    foreach($arr as $rowidx => $row){
        foreach($row as $colidx => $val){
            $out[$ridx][$cidx] = $val;
            $ridx++;
            if($ridx >= $rows){
                $cidx++;
                $ridx = 0;
            }
        }
    }
    

提交回复
热议问题