Iterate Doctrine Collection ordered by some field

后端 未结 4 1453
没有蜡笔的小新
没有蜡笔的小新 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 17:09

    You might add a sort function to Colletion.php :

    public function sortBy( $sortFunction )
    {
        usort($this->data, $sortFunction);
    }  
    

    Sorting a Doctrine_Collection of users by their age would look like this:

    class ExampleClass
    {
    
        public static function sortByAge( $a , $b )
        {
             $age_a = $a->age;
             $age_b = $b->age;
    
             return $age_a == $age_b ? 0 : $age_a > $age_b ? 1 : - 1;
        }    
    
        public function sortExample()
        {
             $users = User::getTable()->findAll();
             $users ->sortBy('ExampleClass::sortByAge');
    
             echo "Oldest User:";
             var_dump ( $users->end() );
        }
    
    }
    

提交回复
热议问题