I have this collection result:
$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
}]
I want to sort the result by date:
$sorted = $transaction->sortBy('date')->values()->all();
But I don't get the expected result:
[{
"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"
}]
As you can see all with month 2 is sort properly. However at month 3 it start messed up. (the real result is longer than this and it messed up start at month 3)
Any solution to make it sort properly?
Thanks.
I had the same problem. I created this macro.
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);
});
I use it like this:
$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);
Try something like this using sortBy():
$sorted = $transaction->sortBy(function($col) {
return $col;
})->values()->all();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With