Doctrine: Sorting a Collection by Array

Let’s assume you have a Doctrine Collection which you want to sort by a custom array of IDs.

To sort a Doctrine Collection you have to use an ArrayCollection:

use Doctrine\Common\Collections\ArrayCollection;$result = $this->getEntityManager()
->createQueryBuilder()
->select('e')
->from('MyEntity', 'e')
->getQuery()
->getResult();

$myArrayCollection = new ArrayCollection($result);

The Doctrine ArrayCollection has different methods for accessing the collection as an array. We will use the getIterator() method to create an ArrayIterator and the uasort() method to create a custom comparison function:

// custom array for sorting by id
$myCustomIdArray = [1331,1212,119];
$myArrayCollectionIterator = $myArrayCollection->getIterator();

$myArrayCollectionIterator->uasort(
function ($first, $second) use ($myCustomIdArray) {
foreach ($myCustomIdArray as $myCustomId) {
if ($first->getCustomId() === $myCustomId) {
return -1;
}
if ($second->getCustomId() === $myCustomId) {
return 1;
}
}
// if value is not found in $myCustomIdArray
return 0;
}
);

$myArrayCollectionIterator is now sorted by the values of $myCustomIdArray.

Web Developer in Berlin — www.kcmueller.de