2d multidimensional array to 1d array in php

后端 未结 8 1812
陌清茗
陌清茗 2021-01-06 00:51

Just wondering if anyone has transformed a 2 dim array to a one dim array in php. I\'ve yet to come across a clear explanation in php. Any suggestion would be appreciated.

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-06 01:34

    The solution for rectangular 2D array is simple indeed, but I had a problem. My 2D-array consisted of 1D arrays of different lengths :

    $myArray = [
        [1, 2, 3, 4],
        [5, 6, 7],
        [8, 9]
    ];
    

    I came up with more generalized solution to turn any 2D array into 1D:

    function array2DTo1D($arr2D) {
        $i = 0; $j = 0;
        $arr1D = [];
        while (isset($arr2D[$i][0])) {
            while (isset($arr2D[$i][$j])) {
                $arr1D[] = $arr2D[$i][$j];
                $j++;
            }
            $i++; $j = 0;
        }
        return $arr1D;
    }
    

提交回复
热议问题