简体   繁体   中英

How to merge 2 arrays - nest one array into another

I have an array:

$form['info'] = array(...);
$form['container'] = array(...);

and I have another array:

$container['item_1'] = array(...);
$container['item_2'] = array(...);

I would like to get a structure like this:

$form['info']
$form['container']['...']
$form['container']['item_1']
$form['container']['item_2']

How could I merge $form and $container array to achieve this? I need to nest/add all items from $container array into $form['container'] variable. array_merge() does not seems to work this way.

This should handle it:

foreach($container as $key => $value){
    $form['container'][$key] = $value;
}
  1. Iterate your $container and get its key-vaule-pairs
  2. Append them to your $form

Why array_merge() is not working? Your task is to merge $form['container'] with $container as I understand. array_merge() can handle this.

$form['container'] = array_merge($form['container'], $container);

Use this

<?php
$form["info"] = array('info');
$form["container"] = array('container');
$container['item_1'] = array('1');
$container['item_2'] = array('2');

foreach($container as $k=>$f)
{
    $form['container'][$k] = $f;
}
print_r($form);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM