我有这个收集结果:
$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
}]
Run Code Online (Sandbox Code Playgroud)
我想按日期对结果进行排序:
$sorted = $transaction->sortBy('date')->values()->all();
Run Code Online (Sandbox Code Playgroud)
但我没有得到预期的结果:
[{
"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"
}]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,第2个月的所有内容都排序正确.然而在第3个月它开始搞砸了.(实际结果比这更长,并且从第3个月开始搞砸了)
任何使其排序正确的解决方案?
谢谢.
尝试是这样的:
$sorted = $transaction->sortBy(function($col)
{
return $col;
})->values()->all();
Run Code Online (Sandbox Code Playgroud)
我有同样的问题。我创建了这个宏。
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);
Run Code Online (Sandbox Code Playgroud)
});
我像这样使用它:
$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);
Run Code Online (Sandbox Code Playgroud)