How to merge two php Doctrine 2 ArrayCollection()
Better (and working) variant for me:
$collection3 = new ArrayCollection( array_merge($collection1->toArray(), $collection2->toArray()));
You can simply do:
$a = new ArrayCollection();$b = new ArrayCollection();...$c = new ArrayCollection(array_merge((array) $a, (array) $b));
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.