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

前端 未结 4 1519
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 16:51

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 righ

4条回答
  •  Happy的楠姐
    2020-12-02 17:23

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

提交回复
热议问题