Jul 29, 2012
kalpesh

Magento, PHP: Merging/Joining two objects collections

It’s easy to merge two arrays with array_merge, but have you came across to merge two objects? It’s not that easy in Magento. You need to convert it to array first, merge them, and convert it to the object again to make it work. If you have two objects of different class, then it’s really difficult job to merge as both will not be compatible. If they are from similar classes or share same elements inside, then it’s not that tricky.

If you want to add collection2 in collection1 (in Magento), where collection1 will be a merged form of both, you can do so by:

foreach($collection2 as $coll) {
    $collection1->addItem($coll);
}


In core PHP, it’s quite easy in this way:

$merged_obj = (object) array_merge( (array) $collection1, (array) $collection2 );

In Magento, converting collection to array is easy:

$arr = $collection->toArray();

while vice versa is difficult as Magento doesn’t have any built-in method to do so.

1 Comment

  • Hello Kalpesh,

    I have tried to set the data of the collection and also the items.But how we can add the custom data in the data part of collection.

    Can you please help me on this ?
    Thanks.

Leave a comment

 

Welcome to my Blog

Kalpesh MehtaHelping Magento developers in their day-to-day development problems since 2011. Most of the problems and solutions here are my own experiences while working on different projects. Enjoy the blog and don't forget to throw comments and likes/+1's/tweets on posts you like. Thanks for visiting!

Certifications

Honor

Recognition

Magento top 50 contributors

Magento top 50 contributors

Contributions