How to merge two php Doctrine 2 ArrayCollection()

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

    You still need to iterate over the Collections to add the contents of one array to another. Since the ArrayCollection is a wrapper class, you could try merging the arrays of elements while maintaining the keys, the array keys in $collection2 override any existing keys in $collection1 using a helper function below:

    $combined = new ArrayCollection(array_merge_maintain_keys($collection1->toArray(), $collection2->toArray())); 
    
    /**
     *  Merge the arrays passed to the function and keep the keys intact.
     *  If two keys overlap then it is the last added key that takes precedence.
     * 
     * @return Array the merged array
     */
    function array_merge_maintain_keys() {
        $args = func_get_args();
        $result = array();
        foreach ( $args as &$array ) {
            foreach ( $array as $key => &$value ) {
                $result[$key] = $value;
            }
        }
        return $result;
    }
    

提交回复
热议问题