foreachLoop
foreachLoop

Reputation: 23

Merging arrays with PHP

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?

Upvotes: 1

Views: 93

Answers (4)

dqhendricks
dqhendricks

Reputation: 19251

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

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77956

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);

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 131841

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);

Upvotes: 0

dynamic
dynamic

Reputation: 48091

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

Upvotes: 1

Related Questions