[英]Laravel collection not properly sort
我尝试使用Laravel函数对我的收藏进行排序。
这是我的数据,例如:
$collection =
[
{
"total_earned": "31739",
"total_spent": "0",
"total_amount": "317390",
"date": "2015-10-01"
}, {
"total_earned": "212622",
"total_spent": "86943",
"total_amount": "2213165",
"date": "2015-12-01"
}, {
"total_earned": 0,
"total_spent": 0,
"total_amount": 0,
"date": "2015-10-29"
}, {
"total_earned": 0,
"total_spent": 0,
"total_amount": 0,
"date": "2015-10-30"
}
];
当我尝试使用Laravel sortBy
函数进行排序并返回时,它变成这样:
[{
"total_earned": 0,
"total_spent": 0,
"total_amount": 0,
"date": "2015-10-29"
}, {
"total_earned": 0,
"total_spent": 0,
"total_amount": 0,
"date": "2015-10-30"
}, {
"total_earned": "212622",
"total_spent": "86943",
"total_amount": "2213165",
"date": "2015-12-01"
}, {
"total_earned": "31739",
"total_spent": "0",
"total_amount": "317390",
"date": "2015-10-01"
}]
如您所见,日期2015-10-01
在底部。 应该在2015-10-29
之前。
我的代码进行排序:
return $transaction->sortBy('date')->values()->all();
这是一个错误还是某种假设?
$transaction = Transaction::dateRange($startDate->format('Ym-d'), $endDate->format('Ym-d')) ->groupBy('merchant_branch_id', DB::raw('DATE(created_at)')) ->selectRaw('DATE(created_at) as date, SUM(point_earned) as total_earned, SUM(point_spent) as total_spent, FLOOR(SUM(amount)) as total_amount') ->orderBy('created_at') ->get(); $convert = $transaction->map(function($item, $key) { $date = Carbon::parse($item->date)->format('Ym-d'); return [$date]; }); $convert = $convert->toArray(); $period = new DatePeriod($startDate, new DateInterval('P1D'), $endDate); foreach ($period as $row) { $date = $row->format('Ym-d'); if (!in_array_r($date, $convert)) { $transaction->push(['date' => $date, 'total_earned' => 0, 'total_spent' => 0, 'total_amount' => 0]); } } $sorted = $transaction->sortBy('date')->values()->all(); return $sorted;
万一其他人遇到同样的问题,您可以尝试从此答案https://stackoverflow.com/a/36170075/1208242使用以下代码:
$sorted = $transaction->sortBy(function($col)
{
return $col;
})->values()->all();
它可能会给您日期错误的顺序(默认情况下,sortBy以“升序”排序,当使用Ymd格式的日期时,显然会返回降序),因此您可以改用sortByDesc()
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.