phparrayssortingsymfonydoctrine

Sorting a Doctrine ArrayCollection by a specific, custom field


I am attempting to sort an ArrayCollection by a specific field. The ArrayCollection is an array of courses. In the Course entity there is a method called isLive which returns a boolean.

I would like to sort this collection to have the "live" courses at the beginning of the array, so that's the courses that return true from a isLive call.

This is the code I have at present, but the first entry in the $sorted array is a non-live course.

$iterator = $this->courses->getIterator();
$iterator->uasort(function ($a, $b) {
   if ($a->isLive() == $b->isLive()) {
      return 0;
   }
   return ($a->isLive() < $b->isLive()) ? -1 : 1;
});
$sorted = new ArrayCollection(iterator_to_array($iterator));

Solution

  • I got to a solution with the use of uasort and array_search as below:

    /**
     * @return ArrayCollection
     */
    public function getCoursesSortedByLive(): ArrayCollection
    {
        $coursesIterator = $this->courses->getIterator();
    
        $sortOrder = [true];
    
        $coursesIterator->uasort(function ($a, $b) use ($sortOrder) {
            return array_search($a->isLive(), $sortOrder) - array_search($b->isLive(), $sortOrder);
        });
    
        return new ArrayCollection(iterator_to_array($sitesIterator));
    }