php Laravel 按日期排序集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36169847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel sort collection by date
提问by ssuhat
I have this collection result:
我有这个收集结果:
$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
}]
I want to sort the result by date:
我想按日期对结果进行排序:
$sorted = $transaction->sortBy('date')->values()->all();
But I don't get the expected result:
但我没有得到预期的结果:
[{
"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"
}]
As you can see all with month 2 is sort properly. However at month 3 it start messed up. (the real result is longer than this and it messed up start at month 3)
正如您所看到的,第 2 个月的所有内容都已正确排序。然而,在第 3 个月,它开始变得一团糟。(实际结果比这更长,而且从第 3 个月开始就搞砸了)
Any solution to make it sort properly?
有什么解决方案可以让它正确排序?
Thanks.
谢谢。
采纳答案by Alexey Mezenin
回答by Raza
I had the same problem. I created this macro.
我有同样的问题。我创建了这个宏。
Collection::macro('sortByDate', function ($column = 'created_at', $order = SORT_DESC) {
/* @var $this Collection */
return $this->sortBy(function ($datum) use ($column) {
return strtotime($datum->$column);
}, SORT_REGULAR, $order == SORT_DESC);
});
I use it like this:
我像这样使用它:
$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);
回答by Dzung Cao
You may try
你可以试试
$transaction->groupBy('date');
And be sure that $transaction is a collection;
并确保 $transaction 是一个集合;