How to merge two php Doctrine 2 ArrayCollection()

前端 未结 8 1038
误落风尘
误落风尘 2020-12-08 01:21

Is there any convenience method that allows me to concatenate two Doctrine ArrayCollection()? something like:

$collection1 = new ArrayCollection         


        
8条回答
  •  再見小時候
    2020-12-08 02:04

    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.

提交回复
热议问题