The Simplest Way to Merge More than One Object In An Array – (PHP-Laravel)

Share on facebook
Share on google
Share on twitter
Share on linkedin

The easiest way to merge more than one object in an array is to convert the objects to array. code shown below:

 $array = [
    {'animal'=>'Dog', 'country'=>'Nigeria'},
    {'company'=>'Oregsideas', 'system'=>'laptop'}
];

 $data = [];
 foreach($array as $arr)
 {
    array_push($data, collect($arr)->toArray());
 }

It’s a very bad practice to use foreach/while/for loop with an array merge function to convert array of arrays because it’s a performance killer on the memory part.

Since PHP 5.6, there is a new operator : the Spread Operator

$array = [
   ['animal'=>'Dog', 'country'=>'Nigeria'],
   ['company'=>'Oregsideas', 'system'=>'laptop']
];

print_r(array_merge([], ...$array));

//Print Preview
$array = [
   [
    'animal'=>'Dog', 'country'=>'Nigeria', 
    'company'=>'Oregsideas', 'system'=>'laptop'
   ],
];

Thank you for reading, and let’s stay in touch !

We hope this article helped you learn how to easily convert array of arrays into one.

If you liked this article, then please subscribe to our channel below by using the subscription input field.

Segun Oregunwa

Segun Oregunwa

Leave a Replay

Sign up for our Newsletter

Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit