使用 Laravel 和 Collection 按日期 DESC 对集合进行排序

Cri*_*eza 2 arrays sorting collections laravel

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

$collection->sortByDesc('total');
Run Code Online (Sandbox Code Playgroud)

为了在总数相等时按降序日期对元素进行排序,我使用了sortandsortByDesc但元素仍然没有排序。

//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');
Run Code Online (Sandbox Code Playgroud)

这两个选项都不适合我,我仍然得到相同的结果:

在此输入图像描述

当结果应如下时(当总值相等时,按下降日期排序项目):

在此输入图像描述

我究竟做错了什么?

PS:它不能帮助我按“总计”排序,然后按“日期”排序,因为“总计”值应该是优先考虑的值。

Rwd*_*Rwd 7

sortByDesc将覆盖您在函数中完成的排序sort

此外,strtotime($a->created_at) - strtotime($b->created_at)将以升序而不是降序对日期进行排序。

以下内容应该可以满足您的需求:

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

    return $a->total < $b->total;
});
Run Code Online (Sandbox Code Playgroud)

最后,假设created_atupdated_atCarbon您不需要使用的实例strtotime

$a->created_at < $b->created_at
Run Code Online (Sandbox Code Playgroud)