“usort” a Doctrine\Common\Collections\ArrayCollection?

2022-08-30 09:03:25

在各种情况下,我需要根据对象中的属性对 a 进行排序。在没有找到立即做到这一点的方法的情况下,我这样做:Doctrine\Common\Collections\ArrayCollection

// $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


答案 1

要对现有集合进行排序,您需要查找 ArrayCollection::getIterator() 方法,该方法返回一个 ArrayIterator。例:

$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
    return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));

最简单的方法是让存储库中的查询处理您的排序。

想象一下,您有一个与类别实体具有多对多关系的超级实体。

然后,例如创建一个存储库方法,如下所示:

// 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()
    ;
}

...使排序变得非常容易。

希望有所帮助。


答案 2

从原则 2.3 开始,您可以使用标准 API

例如:

<?php

public function getSortedComments()
{
    $criteria = Criteria::create()
      ->orderBy(array("created_at" => Criteria::ASC));

    return $this->comments->matching($criteria);
}

注意:此解决方案需要对属性或公共 getter 方法进行公共访问。$createdAtgetCreatedAt()


推荐