"usort" a Doctrine\Common\Collections\ArrayCollection?
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.
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.
Hope that helps.
Since Doctrine 2.3 you can use the Criteria API
Eg:
<?php
public function getSortedComments()
{
$criteria = Criteria::create()
->orderBy(array("created_at" => Criteria::ASC));
return $this->comments->matching($criteria);
}
Note: this solution requires public access to
$createdAt
property or a public getter methodgetCreatedAt()
.