Merge array inside array
Asked Answered
C

4

6

I have 2 arrays to merge. The first array is multidimensional, and the second array is a single array:

$a = array(
    array('id'=>'1', 'name'=>'Mike'),
    array('id'=>'2', 'name'=>'Lina'),
);

$b = array('id'=>'3', 'name'=>'Niken');

How to merge 2 arrays to have same array depth?

Cutaneous answered 5/10, 2016 at 12:29 Comment(1)
What is your desired result?Hypso
G
7

If what you want is this:

array(
    array('id'=>'1', 'name'=>'Mike'),
    array('id'=>'2', 'name'=>'Lina'),
    array('id'=>'3', 'name'=>'Niken')
)

You can just add the second as a new element to the first:

$one[] = $two;
Guzman answered 5/10, 2016 at 12:32 Comment(1)
Exactly what I thoughtSob
N
1

Just append the second array with an empty dimension operator.

$one = array(
    array('id'=>'1', 'name'=>'Mike'),
    array('id'=>'2', 'name'=>'Lina')
);

$two = array('id'=>'3', 'name'=>'Niken');

$one[] = $two;

But if you're wanting to merge unique items, you'll need to do something like this:

if(false === array_search($two, $one)){
    $one[] = $two;
}
Neologism answered 5/10, 2016 at 12:31 Comment(0)
I
1

You can easily do this with the array push with the current array, i modified your code so it would work

<?php
  $myArray = array(
    array('id' => '1',  'name' => 'Mike'),
    array('id' => '2',  'name '=> 'Lina')
  );
  array_push($myArray, array('id'=>'3', 'name'=>'Niken'));
  // Now $myArray has all three of the arrays
  var_dump($myArray);
?>

Let me know if this helps

Incubator answered 5/10, 2016 at 13:39 Comment(0)
F
0

For inserting anything into array you can just use push over index ($array[] = $anything;) or array_push() function. Your case can use both approaches.

Firebug answered 5/10, 2016 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.