Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 221
Stfvns Avatar asked Oct 05 '16 12:10

Stfvns


People also ask

How do I merge an array of arrays into a single array?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do I combine two arrays into a new array?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

How do I combine two arrays?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.


2 Answers

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;
like image 145
sidyll Avatar answered Sep 26 '22 19:09

sidyll


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;
}
like image 29
calcinai Avatar answered Sep 24 '22 19:09

calcinai