Is there any convenience method that allows me to concatenate two Doctrine ArrayCollection()
? something like:
$collection1 = new ArrayCollection();
$collection2 = new ArrayCollection();
$collection1->add($obj1);
$collection1->add($obj2);
$collection1->add($obj3);
$collection2->add($obj4);
$collection2->add($obj5);
$collection2->add($obj6);
$collection1->concat($collection2);
// $collection1 now contains {$obj1, $obj2, $obj3, $obj4, $obj5, $obj6 }
I just want to know if I can save me iterating over the 2nd collection and adding each element one by one to the 1st collection.
Thanks!
You can simply do:
You still need to iterate over the Collections to add the contents of one array to another. Since the ArrayCollection is a wrapper class, you could try merging the arrays of elements while maintaining the keys, the array keys in $collection2 override any existing keys in $collection1 using a helper function below:
Using Clousures PHP5 > 5.3.0
Based on Yury Pliashkou's comment:
Maybe you like it... maybe not... I just thought of throwing it out there just in case someone needs it.
Better (and working) variant for me:
If you are required to prevent any duplicates, this snippet might help. It uses a variadic function parameter for usage with PHP5.6.
Might be handy in some cases.