简体   繁体   中英

Laravel sort collection by date

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.

Try something like this :

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

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);

You may try

$transaction->groupBy('date');

And be sure that $transaction is a collection;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM