2d multidimensional array to 1d array in php

后端 未结 8 1786
陌清茗
陌清茗 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:29

    Try this one:

    function array_to1d($a) {
        $out = array();
        foreach ($a as $b) {
            foreach ($b as $c) {
                if (isset($c)) {
                    $out[] = $c;
                }
            }
        }
        return $out;
    }
    

    Notice that it includes a test to see if the value is set (non-null). An array that's a transposition of an array with rows of varying length will have null values in some cells, and this check can be helpful if you're trying to linearize such a beast.

提交回复
热议问题