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?

1
  • 1
    What is your desired result? Commented Oct 5, 2016 at 12:30

4 Answers 4

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

1 Comment

Exactly what I thought
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;
}

Comments

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

Comments

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.

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.