我尝试使用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('Y-m-d'), $endDate->format('Y-m-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('Y-m-d');
return [$date];
});
$convert = $convert->toArray();
$period = new DatePeriod($startDate, new DateInterval('P1D'), $endDate);
foreach ($period as $row) {
$date = $row->format('Y-m-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;
答案 0 :(得分:0)
如果有其他人遇到同样问题的问题,您可以尝试使用此答案中的以下代码https://stackoverflow.com/a/36170075/1208242:
$sorted = $transaction->sortBy(function($col)
{
return $col;
})->values()->all();
它可能会以错误的顺序为您提供日期(sortBy默认以'升序'顺序排序,显然在处理Ymd格式的日期时返回降序),因此您可以使用sortByDesc()
方法代替< / p>