How to merge two php Doctrine 2 ArrayCollection()

前端 未结 8 1033
误落风尘
误落风尘 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:25

    Attention! Avoid large nesting of recursive elements. array_unique - has a recursive embedding limit and causes a PHP error Fatal error: Nesting level too deep - recursive dependency?

    /**
     * @param ArrayCollection[] $arrayCollections
     *
     * @return ArrayCollection
     */
    function merge(...$arrayCollections) {
        $listCollections = [];
        foreach ($arrayCollections as $arrayCollection) {
            $listCollections = array_merge($listCollections, $arrayCollection->toArray());
        }
    
        return new ArrayCollection(array_unique($listCollections, SORT_REGULAR));
    }
    
    // using
    $a = new ArrayCollection([1,2,3,4,5,6]);
    $b = new ArrayCollection([7,8]);
    $c = new ArrayCollection([9,10]);
    
    $result = merge($a, $b, $c);
    

提交回复
热议问题