Merge an array inside an array

I have 2 arrays to combine. 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 combine 2 arrays have the same array?

+5
source share
4 answers

If you want this:

 array( array('id'=>'1', 'name'=>'Mike'), array('id'=>'2', 'name'=>'Lina'), array('id'=>'3', 'name'=>'Niken') ) 

You can simply add the second as a new element to the first:

 $one[] = $two; 
+7
source

Just add a second array with an empty dimension statement.

 $one = array( array('id'=>'1', 'name'=>'Mike'), array('id'=>'2', 'name'=>'Lina') ); $two = array('id'=>'3', 'name'=>'Niken'); $one[] = $two; 

But if you want to combine unique elements, you need to do something like this:

 if(false === array_search($two, $one)){ $one[] = $two; } 
+1
source

You can easily do this with the push array with the current array, I modified your code to make it 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.

+1
source

To insert something into an array, you can simply use push over index ($ array [] = $ anything;) or array_push () . In your case both approaches can be used.

0
source

Source: https://habr.com/ru/post/1257731/


All Articles