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

前端 未结 23 2160
没有蜡笔的小新
没有蜡笔的小新 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:16

    function flatten_array($array, $preserve_keys = 0, &$out = array()) {
        # Flatten a multidimensional array to one dimension, optionally preserving keys.
        #
        # $array - the array to flatten
        # $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
        # $out - internal use argument for recursion
        foreach($array as $key => $child)
            if(is_array($child))
                $out = flatten_array($child, $preserve_keys, $out);
            elseif($preserve_keys + is_string($key) > 1)
                $out[$key] = $child;
            else
                $out[] = $child;
        return $out;
    }
    

提交回复
热议问题