Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel sort by keys

I make an array with collections with code:

$hours = Voucher::where('created_at','>=', Carbon::now()->startOfMonth())->get()->groupBy(function($item)
{
  return $item->created_at->format('H');
});

dd($hours);

so I get data like this:

enter image description here

SO keys are hours (00-23).

How I can arrange it starting by 00, 01, 02, 03 ... ...

like image 941
Aleks Per Avatar asked Jan 27 '23 13:01

Aleks Per


1 Answers

https://laravel.com/docs/5.6/collections#method-sortkeys

$collection = collect([
    'id' => 22345,
    'first' => 'John',
    'last' => 'Doe',
]);

$sorted = $collection->sortKeys();

Update for 5.1

Since you're using Laravel 5.1 and there is no sortKeys method, you can sort the collection before you group it which should result in the keys being in the correct order.

$collection->sort(function($a, $b) {
    return strcmp($a->created_at->format('H'), $b->created_at->format('H'));
})->groupBy(function($item) {
    return $item->created_at->format('H');
});
like image 119
Devon Avatar answered Feb 08 '23 01:02

Devon