拉拉维尔集合未正确排序


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('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;

以防万一其他人遇到同样的问题,您可以尝试使用此答案 https://stackoverflow.com/a/36170075/1208242 中的以下代码:

$sorted = $transaction->sortBy(function($col)
{
    return $col;
})->values()->all();

它可能会以错误的顺序为您提供日期(默认情况下按"升序"排序,在处理 Y-m-d 格式的日期时显然会返回降序),因此您可以使用sortByDesc()方法来代替