" usort"一个Doctrine\Common\Collections\ArrayCollection? [英] "usort" a Doctrine\Common\Collections\ArrayCollection?
问题描述
在各种情况下,我需要根据对象中的属性对 Doctrine\Common\Collections\ArrayCollection
进行排序。没有找到一个这样做的方法,我这样做:
In various cases I need to sort a Doctrine\Common\Collections\ArrayCollection
according to a property in the object. Without finding a method doing that right away, I do this:
// $collection instanceof Doctrine\Common\Collections\ArrayCollection
$array = $collection->getValues();
usort($array, function($a, $b){
return ($a->getProperty() < $b->getProperty()) ? -1 : 1 ;
});
$collection->clear();
foreach ($array as $item) {
$collection->add($item);
}
我认为这不是将所有内容复制到本地的最好方式PHP数组和后面。我想知道是否有更好的方法来usort一个 Doctrine\Common\Collections\ArrayCollection
。我想念任何文件?
I presume this is not the best way when you have to copy everything to native PHP array and back. I wonder if there is a better way to "usort" a Doctrine\Common\Collections\ArrayCollection
. Do I miss any doc?
推荐答案
要排序现有的集合,您正在寻找 ArrayCollection :: getIterator() 方法返回一个ArrayIterator。例如:
To sort an existing Collection you are looking for the ArrayCollection::getIterator() method which returns an ArrayIterator. example:
$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));
最简单的方法是让存储库中的查询处理排序。
The easiest way would be letting the query in the repository handle your sorting.
想象一下,您有一个具有与实体的ManyToMany关系的SuperEntity。
Imagine you have a SuperEntity with a ManyToMany relationship with Category entities.
然后例如创建存储库方法像这样:
Then for instance creating a repository method like this:
// Vendor/YourBundle/Entity/SuperEntityRepository.php
public function findByCategoryAndOrderByName($category)
{
return $this->createQueryBuilder('e')
->where('e.category = :category')
->setParameter('category', $category)
->orderBy('e.name', 'ASC')
->getQuery()
->getResult()
;
}
...使排序很容易。
... makes sorting pretty easy.
希望有帮助。
这篇关于" usort"一个Doctrine\Common\Collections\ArrayCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!