PHP convert nested array to single array while concatenating keys?

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

Here is an example array:

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


        
7条回答
  •  春和景丽
    2020-12-10 05:05

    This will flatten a multidimensional associative array tacking a digit to the key if its a duplicate. If you don't mind having a digit index to differentiate duplicate keys instead of concatenated keys this could be a solution.

    $result = array();
    array_walk_recursive($your_array, function($v, $k) use (&$result){ $i = ""; for (; isset($result[$k."$i"]); $i++); $result[$k."$i"] = $v; });
    

    I suspect it could be worked on further to do concatenated keys.

    The above solution is basically for doing this kind of thing

    
            
                0                  
            
            
                10
            
        ";
                        // turn the xml into a multidimentional array
                $ob = simplexml_load_string($xml_str);
                $json = json_encode($ob);
                $my_array = json_decode($json, true);
    
                print_r($my_array);
                        // flatten it
                $result = array();
                array_walk_recursive($my_array, function($v, $k) use (&$result){ $i = ""; for (; isset($result[$k."$i"]); $i++); $result[$k."$i"] = $v; });
    
                print_r($result);
    ?>
    

提交回复
热议问题