PHP convert nested array to single array while concatenating keys?

前端 未结 7 1000
我在风中等你
我在风中等你 2020-12-10 04:24

Here is an example array:

 $foo = array(
           \'employer\' => array(
                    \'name\' => \'Foobar Inc\',
                    \'phone\         


        
7条回答
  •  盖世英雄少女心
    2020-12-10 05:02

    After a few iterations, I've been able to refine a solution to this problem that uses a stack-based approach to avoid recursion, simplifying things a bit.

    /***
     * @name array_flatten
     * @author Tom Penzer @tpenzer
     * Flattens a multi-tiered array into a single-tiered 
     * associative array with keys reflective of their 
     * values' hierarchy.
     *
     * @param    array    $array       Required - the multi- 
     * level keyed array to be flattened
     * @param    string   $separator   Optional - the string 
     * used to separate the keys from different levels of 
     * the hierarchy
     *
     * @return   array    a single-level keyed array
     ***/
    function array_flatten($array, $separator = '_') {
        $output = array();
    
        while (list($key, $value) = each($array)) {
            if (is_array($value)) {
                $build = array();
                foreach ($value as $s_key => $s_value) {
                    $build[$key . $separator . $s_key] = $s_value;
                }
                unset($array[$key]);
                $array = $build + $array;
                unset($build);
                continue;//skip write to $output
            }
            $output[$key] = $value;
            unset($array[$key]);
        }
    
        return $output;
    }
    

    Not exactly the method requested, but it's a nice contrast to the recursive approaches to the problem.

提交回复
热议问题