Convert multidimensional array into single array

后端 未结 20 1792
时光取名叫无心
时光取名叫无心 2020-11-22 10:39

I have an array which is multidimensional for no reason

/* This is how my array is currently */
Array
(
[0] => Array
    (
        [0] => Array
                


        
20条回答
  •  孤独总比滥情好
    2020-11-22 11:22

    none of answers helped me, in case when I had several levels of nested arrays. the solution is almost same as @AlienWebguy already did, but with tiny difference.

    function nestedToSingle(array $array)
    {
        $singleDimArray = [];
    
        foreach ($array as $item) {
    
            if (is_array($item)) {
                $singleDimArray = array_merge($singleDimArray, nestedToSingle($item));
    
            } else {
                $singleDimArray[] = $item;
            }
        }
    
        return $singleDimArray;
    }
    

    test example

    $array = [
            'first',
            'second',
            [
                'third',
                'fourth',
            ],
            'fifth',
            [
                'sixth',
                [
                    'seventh',
                    'eighth',
                    [
                        'ninth',
                        [
                            [
                                'tenth'
                            ]
                        ]
                    ],
                    'eleventh'
                ]
            ],
            'twelfth'
        ];
    
        $array = nestedToSingle($array);
        print_r($array);
    
        //output
        array:12 [
            0 => "first"
            1 => "second"
            2 => "third"
            3 => "fourth"
            4 => "fifth"
            5 => "sixth"
            6 => "seventh"
            7 => "eighth"
            8 => "ninth"
            9 => "tenth"
            10 => "eleventh"
            11 => "twelfth"
       ]
    

提交回复
热议问题