1

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.

6
  • What code (exactly) are you using in attempt to merge? Could you supply source? Commented Apr 20, 2016 at 9:24
  • How have you used array_merge()? Commented Apr 20, 2016 at 9:25
  • The source is too complicated so I made this simple example. Commented Apr 20, 2016 at 9:26
  • @dr_debug array_merge($form, $container); Commented Apr 20, 2016 at 9:28
  • $form['container']['item_1'] it will give you merged array with container and item1 values. right? Commented Apr 20, 2016 at 9:29

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is a proper solution.
1

This should handle it:

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

1 Comment

Thanks, this works. I think there is no native php function for this kind of merging.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.