如何合并两个php Doctrine 2 ArrayCollection()

有没有什么方便的方法可以连接两个Doctrine ArrayCollection() ? 就像是:

 $collection1 = new ArrayCollection(); $collection2 = new ArrayCollection(); $collection1->add($obj1); $collection1->add($obj2); $collection1->add($obj3); $collection2->add($obj4); $collection2->add($obj5); $collection2->add($obj6); $collection1->concat($collection2); // $collection1 now contains {$obj1, $obj2, $obj3, $obj4, $obj5, $obj6 } 

我只想知道是否可以省去迭代第二个集合,并将每个元素逐个添加到第一个集合中。

谢谢!

更好的(和工作)变种对我来说:

 $collection3 = new ArrayCollection( array_merge($collection1->toArray(), $collection2->toArray()) ); 

你可以简单地做:

 $a = new ArrayCollection(); $b = new ArrayCollection(); ... $c = new ArrayCollection(array_merge((array) $a, (array) $b)); 

如果您需要防止重复,这个片段可能会有所帮助。 它使用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; } 

在某些情况下可能会得心应手。

 $newCollection = new ArrayCollection((array)$collection1->toArray() + $collection2->toArray()); 

这应该比array_merge快。 在$collection2存在相同的键名称时,将保留$collection1中的重复键名称。 不pipe实际的价值是多less

您仍然需要遍历集合以将一个数组的内容添加到另一个。 由于ArrayCollection是一个包装类,您可以在维护键的同时尝试合并元素数组,$ collection2中的数组键使用下面的帮助函数覆盖$ collection1中的任何现有键:

 $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; } 

基于Yury Pliashkou的评论:

 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; } 

也许你喜欢它……也许不是……我只是想把它扔出去,以防万一有人需要它。

使用Clousures PHP5> 5.3.0

 $a = ArrayCollection(array(1,2,3)); $b = ArrayCollection(array(4,5,6)); $b->forAll(function($key,$value) use ($a){ $a[]=$value;return true;}); echo $a.toArray(); array (size=6) 0 => int 1 1 => int 2 2 => int 3 3 => int 4 4 => int 5 5 => int 6