How to “flatten” a multi-dimensional array to simple one in PHP?

前端 未结 23 2108
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 01:03

It\'s probably beginner question but I\'m going through documentation for longer time already and I can\'t find any solution. I thought I could use implode for each dimensio

23条回答
  •  爱一瞬间的悲伤
    2020-11-22 01:14

    Using higher-order functions (note: I'm using inline anonymous functions, which appeared in PHP 5.3):

    function array_flatten($array) {
        return array_reduce(
            $array,
            function($prev, $element) {
                if (!is_array($element))
                    $prev[] = $element;
                else
                    $prev = array_merge($prev, array_flatten($element));
                return $prev;
            },
            array()
        );
    }
    

提交回复
热议问题