我有这个收集结果:
$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"
}]
正如您所看到的,第2个月的所有内容都排序正确。然而在第3个月它开始搞砸了。 (实际结果比这长,并且从第3个月开始搞砸了)
任何使其排序正确的解决方案?
感谢。
答案 0 :(得分:6)
尝试like this:
$sorted = $transaction->sortBy(function($col)
{
return $col;
})->values()->all();
答案 1 :(得分:0)
您可以尝试
$transaction->groupBy('date');
确保$ transaction是一个集合;
答案 2 :(得分:0)
我遇到了同样的问题。我创建了这个宏。
@foreach ($players as $key => $player)
我这样用:
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);
});