首页 > 解决方案 > 使用 Laravel 和 Collection 按日期 DESC 对集合进行排序

问题描述

我有一个集合,我以降序方式对“总”值进行排序。当“总”值相同时,我必须按日期降序排列项目。

$collection->sortByDesc('total');

当总数相等时按降序对元素进行排序,我使用了sortsortByDesc但元素仍未排序。

//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:按“总计”然后按“日期”排序对我没有帮助,因为“总计”值是应该优先考虑的值。

标签: arrayslaravelsortingcollections

解决方案


sortByDesc will override the sorting you've done in your sort function.

Also, strtotime($a->created_at) - strtotime($b->created_at) will order the dates in ascending order not descending order.

The following should give you what you're after:

$collection->sort(function ($a, $b) {
    if ($a->total === $b->total) {
        return strtotime($a->created_at) < strtotime($b->created_at);
    }

    return $a->total < $b->total;
});

Lastly, assuming that created_at and updated_at are Carbon instances you shouldn't need to use strtotime:

$a->created_at < $b->created_at

推荐阅读