Stfvns
Stfvns

Reputation: 1041

Merge array inside array

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?

Upvotes: 6

Views: 656

Answers (4)

Andrej Buday
Andrej Buday

Reputation: 609

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

Upvotes: 0

CodeNow
CodeNow

Reputation: 34

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

Upvotes: 1

calcinai
calcinai

Reputation: 2617

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

Upvotes: 1

sidyll
sidyll

Reputation: 59277

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;

Upvotes: 7

Related Questions