How to merge two php Doctrine 2 ArrayCollection()

前端 未结 8 1032
误落风尘
误落风尘 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);
    
    0 讨论(0)
  • 2020-12-08 02:27

    Add a Collection to an array, based on Yury Pliashkou's comment (I know it does not directly answer the original question, but that was already answered, and this could help others landing here):

    function addCollectionToArray( $array , $collection ) {
        $temp = $collection->toArray();
        if ( count( $array ) > 0 ) {
            if ( count( $temp ) > 0 ) {
                $result = array_merge( $array , $temp );
            } else {
                $result = $array;
            }
        } else {
            if ( count( $temp ) > 0 ) {
                $result = $temp;
            } else {
                $result = array();
            }
        }
        return $result;
    }
    

    Maybe you like it... maybe not... I just thought of throwing it out there just in case someone needs it.

    0 讨论(0)
提交回复
热议问题