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

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

    A new approach based on the previous example function submited by chaos, which fixes the bug of overwritting string keys in multiarrays:

    # 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
    
    function flatten_array($array, $preserve_keys = 2, &$out = array(), &$last_subarray_found) 
    {
            foreach($array as $key => $child)
            {
                if(is_array($child))
                {
                    $last_subarray_found = $key;
                    $out = flatten_array($child, $preserve_keys, $out, $last_subarray_found);
                }
                elseif($preserve_keys + is_string($key) > 1)
                {
                    if ($last_subarray_found)
                    {
                        $sfinal_key_value = $last_subarray_found . "_" . $key;
                    }
                    else
                    {
                        $sfinal_key_value = $key;
                    }
                    $out[$sfinal_key_value] = $child;
                }
                else
                {
                    $out[] = $child;
                }
            }
    
            return $out;
    }
    
    Example:
    $newarraytest = array();
    $last_subarray_found = "";
    $this->flatten_array($array, 2, $newarraytest, $last_subarray_found);
    

提交回复
热议问题