"usort" a Doctrine\Common\Collections\ArrayCollection?

PhpDoctrine Orm

Php Problem Overview


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

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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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 method getCreatedAt().

Solution 3 - Php

If you have an ArrayCollection field you could order with annotations. eg:

Say an Entity named Society has many Licenses. You could use

/**
* @ORM\OneToMany(targetEntity="License", mappedBy="society")
* @ORM\OrderBy({"endDate" = "DESC"})
**/
private $licenses;

That will order the ArrayCollection by endDate (datetime field) in desc order.

See Doctrine documentation: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#orderby

Solution 4 - Php

Doctrine criteria does not allow to order by a property on a related object.

If you want to do it (like me), you have to use the uasort method of the Iterator like a previous response and if you use PHP 7, you can use the Spaceship operator <=> like this :

/** @var \ArrayIterator $iterator */
$iterator = $this->optionValues->getIterator();
$iterator->uasort(function (ProductOptionValue $a, ProductOptionValue $b) {
    return $a->getOption()->getPosition() <=> $b->getOption()->getPosition();
});

return new ArrayCollection(iterator_to_array($iterator));

Solution 5 - Php

In last Symfony 5.3 without @annotations you just need

...
#[OrderBy(['sortOrder' => 'ASC'])]
private Collection $collection;

#[Column(type: 'integer')]
private int $sortOrder = 0;
...

in your entity

Solution 6 - Php

How about getting all values, sorting these values, and then overwriting the property with the sorted values?

public function sortMyDateProperty(): void
{
    $values = $this->myAwesomeCollection->getValues();
    usort($values, static function (MyAwesomeInterface $a, MyAwesomeInterface $b): int {
        if ($a->getMyDateProperty()->getTimestamp() === $b->getMyDateProperty()->getTimestamp()) {
            return 0;
        }

        return $a->getMyDateProperty() > $b->getMyDateProperty() ? 1 : -1;
    });

    $this->myAwesomeCollection = new ArrayCollection($values);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionluiges90View Question on Stackoverflow
Solution 1 - PhpNicolai FröhlichView Answer on Stackoverflow
Solution 2 - PhpioleoView Answer on Stackoverflow
Solution 3 - PhpakrzView Answer on Stackoverflow
Solution 4 - PhpFabien SallesView Answer on Stackoverflow
Solution 5 - Phpuser1921553View Answer on Stackoverflow
Solution 6 - PhpJulianView Answer on Stackoverflow