Iterate Doctrine Collection ordered by some field

后端 未结 4 1477
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 16:34

I need something like this:

        $products = Products::getTable()->find(274);
        foreach ($products->Categories->orderBy(\'title\') as $category         


        
4条回答
  •  遇见更好的自我
    2021-02-19 16:52

    You could use collection iterator:

    $collection = Table::getInstance()->findAll();
    
    $iter = $collection->getIterator();
    $iter->uasort(function($a, $b) {
      $name_a = (int)$a->getName();
      $name_b = (int)$b->getName();
    
      return $name_a == $name_b ? 0 : $name_a > $name_b ? 1 : - 1;
    });        
    
    foreach ($iter as $element) {
      // ... Now you could iterate sorted collection
    }
    

    If you want to sort collection using __toString method, it will be much easier:

    foreach ($collection->getIterator()->asort() as $element) { /* ... */ }
    

提交回复
热议问题