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?

ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
Stfvns
  • 1,001
  • 5
  • 16
  • 42

4 Answers4

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;
sidyll
  • 57,726
  • 14
  • 108
  • 151
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;
}
calcinai
  • 2,567
  • 14
  • 25
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

CodeNow
  • 34
  • 5
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.

Andrej Buday
  • 559
  • 5
  • 14