开发者

Merging arrays with PHP

开发者 https://www.devze.com 2023-03-22 05:53 出处:网络
Here is my array: array( \'username\' => \'Username cannot be empty\', \'password\' => \'Password cannot be empty\',

Here is my array:

array(
    'username' => 'Username cannot be empty',
    'password' => 'Password cannot be empty',
    '_external' => array(
        'email' => 'Email cannot be empty',
    ),
),

... and I want to get this result from my array:

array(
    'username' => 'Username cannot be empty',
    'password' => 'Password cannot be empty',
    'email' => 'Email cannot be empty',
),

I know how to do this with 开发者_高级运维foreach loop, but it's too big code. Is there any short and fast method to do this?


foreach($array as $k=>$v) {
  if (is_array($array[$k])) {
   $array = array_merge($array,$array[$k]);
   unset($array[$k]);
  } 
}


foreach (array_keys($array) as $key) {
  $value = $array[$key];
  if (is_array($value)) {
    unset($array[$key]);
    $array = array_merge($array, $value);
  }
}

After the edit of the question its much simpler

$x = $array['_external'];
unset($array['_external']);
$array = array_merge($array, $x);


Try this. Less verbose:

$tmp_obj = (object) array('flatten' => array());  
array_walk_recursive($my_multidim_array, create_function('&$v, $k, &$t', '$t->flatten[] = $v;'), $tmp_obj);

var_dump($tmp_obj->flatten);


array_splice($array, 2, 1, $array[2]);
0

精彩评论

暂无评论...
验证码 换一张
取 消