我有一个集合,其中我以降序方式对"total"值进行排序。当"total"值相同时,我必须按降序日期对项目进行排序。
$collection->sortByDesc('total');
为了在总数相等时按降序日期对元素进行排序,我使用了sort
和sortByDesc
,但元素仍然没有排序。
//First method
$collection->sortByDesc('created_at')->sortByDesc('total');
//Second method
$collection->->sort(function($a, $b){
if($a->total === $b->total)
{
return strtotime($a->created_at) - strtotime($b->created_at);
}
})->sortByDesc('total');
这两种选择对我都不起作用,我仍然得到相同的结果:
当结果如下时(当总值相等时,项目按下降日期排序):
我哪里做错了?
PS:先按"总计"再按"日期"排序对我没有帮助,因为"总计"值才是应该优先考虑的值。
1条答案
按热度按时间xytpbqjk1#
sortByDesc
将覆盖您在sort
函数中完成的排序。此外,
strtotime($a->created_at) - strtotime($b->created_at)
将按升序而不是降序对日期进行排序。以下内容应该能给予您的需求:
最后,假设
created_at
和updated_at
是Carbon
示例,您不需要使用strtotime
: