How to merge two php Doctrine 2 ArrayCollection()
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!
Solution 1:
Better (and working) variant for me:
$collection3 = new ArrayCollection(
array_merge($collection1->toArray(), $collection2->toArray())
);
Solution 2:
You can simply do:
$a = new ArrayCollection();
$b = new ArrayCollection();
...
$c = new ArrayCollection(array_merge((array) $a, (array) $b));
Solution 3:
If you are required to prevent any duplicates, this snippet might help. It uses a variadic function parameter for usage with PHP5.6.
/**
* @param array... $arrayCollections
* @return ArrayCollection
*/
public function merge(...$arrayCollections)
{
$returnCollection = new ArrayCollection();
/**
* @var ArrayCollection $arrayCollection
*/
foreach ($arrayCollections as $arrayCollection) {
if ($returnCollection->count() === 0) {
$returnCollection = $arrayCollection;
} else {
$arrayCollection->map(function ($element) use (&$returnCollection) {
if (!$returnCollection->contains($element)) {
$returnCollection->add($element);
}
});
}
}
return $returnCollection;
}
Might be handy in some cases.
Solution 4:
$newCollection = new ArrayCollection((array)$collection1->toArray() + $collection2->toArray());
This should be faster than array_merge
. Duplicate key names from $collection1
are kept when same key name is present in $collection2
. No matter what the actual value is