PHP convert nested array to single array while concatenating keys?

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

Here is an example array:

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


        
7条回答
  •  無奈伤痛
    2020-12-10 05:06

    I think this 'trick' using is http_build_query is less of an eyesore w/out recursion (or at least letting php do it for you)

    3 lines of code if your str_replace uses the url-encoded values for [ and ]

    $string      = http_build_query($array);
    $string      = urldecode($string);
    $string      = str_replace(
                        array('[',']'),
                        array('_','') , 
                        $string
                    );
    parse_str($string, $flat_array);
    

    $flat_array becomes :

    array(7) {
      ["employer_name"]         =>"Foobar Inc"
      ["employer_phone"]        =>"555-555-5555"
      ["employee_name"]         =>"John Doe"
      ["employee_phone"]        =>"555-555-5556"
      ["employee_address_state"]=>"California"
      ["employee_address_zip"]  =>"90210"
      ["modified"]              =>"2009-12-01"
    }
    

提交回复
热议问题