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?
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.
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.
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.
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;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With