Sort Laravel collections by date

I have the result of this collection:

$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 do not 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, everything with month 2 is sorted correctly. However, in the 3rd month it all started. (the real result is longer than this, and it got confused at the beginning of the month)

Any solution for proper sorting?

Thank.

+4
source share
3 answers

Try something like this :

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

You can try

$transaction->groupBy('date');

And make sure $ transaction is a collection;

0
source

. .

Collection::macro('sortByDate', function ($column = 'created_at', $order = SORT_DESC) {
    /* @var $this Collection */
    return $this->sortBy(function ($comment) use ($column) {
        return strtotime($comment->$column);
    }, SORT_REGULAR, $order == SORT_DESC);
});

:

$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);
0

All Articles