Laravel按日期对收藏进行排序


Laravel sort collection by date

我有这个收集结果:

$result = [{
    "date": "2016-03-21",
    "total_earned": "101214.00"
},
{
    "date": "2016-03-22",
    "total_earned": "94334.00"
},
{
    "date": "2016-03-23",
    "total_earned": "96422.00"
},
{
    "date": "2016-02-23",
    "total_earned": 0
},
{
    "date": "2016-02-24",
    "total_earned": 0
},
{
    "date": "2016-02-25",
    "total_earned": 0
}]

我想按日期对结果进行排序:

$sorted = $transaction->sortBy('date')->values()->all();

但我没有得到预期的结果:

[{
    "date": "2016-02-23",
    "total_earned": 0
},
{
    "date": "2016-02-24",
    "total_earned": 0
},
{
    "date": "2016-02-25",
    "total_earned": 0
},
{
    "date": "2016-03-22",
    "total_earned": "94334.00"
},
{
    "date": "2016-03-21",
    "total_earned": "101214.00"
},
{
    "date": "2016-03-23",
    "total_earned": "96422.00"
}]

正如你所看到的,第二个月的排序是正确的。然而,在第三个月,它开始变得一团糟。(实际结果比这更长,从第3个月开始就搞砸了)

有什么解决方案可以让它正确分类吗?

谢谢。

我也遇到了同样的问题。我创建了这个宏。

Collection::macro('sortByDate', function (string $column = 'created_at', bool $descending = true) {
/* @var $this Collection */
return $this->sortBy(function ($datum) use ($column) {
    return strtotime(((object)$datum)->$column);
}, SORT_REGULAR, $descending);

});

我是这样使用的:

$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);

使用sortBy:尝试类似的操作

$sorted = $transaction->sortBy(function($col) {
    return $col;
})->values()->all();

您可以尝试

$transaction->groupBy('date');

并确保$transaction是一个集合;