PHP convert nested array to single array while concatenating keys?

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

Here is an example array:

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


        
7条回答
  •  时光取名叫无心
    2020-12-10 05:02

    Here is a function which allows you to specify a top-level prefix via the second parameter:

    function flatten_array($array, $prefix = null) {
      if ($prefix) $prefix .= '_';
    
      $items = array();
    
      foreach ($array as $key => $value) {
        if (is_array($value))
          $items = array_merge($items,  flatten_array($value, $prefix . $key));
        else
          $items[$prefix . $key] = $value;
      }
    
      return $items;
    }
    

提交回复
热议问题