Hashan
Hashan

Reputation: 184

Sort array from days Laravel 5.8

I want to sort an array according to the days name order. here is my array comes from query result.

        $data = DB::table('jobs')
                ->select('day', DB::raw('count(*) as count'))
                ->groupBy('day')
                ->get()->toArray();

Output is:

enter image description here

I send this data to draw a bar chart with chart.js , so I want to sort this array from Monday to Friday. I'm new to laravel. please help me to solve this. thank you in advance.

Upvotes: 0

Views: 687

Answers (3)

IGP
IGP

Reputation: 15786

You could sort them based on the carbon day constants.

Carbon\Carbon::SUNDAY evaluates to 0, Carbon\Carbon::MONDAY evaluates to 1 all the way to Carbon\Carbon::SATURDAY evaluating to 6.

To programatically get a constant, you can use the constant($string) method.

$data = DB::table('jobs')
    ->select('day', DB::raw('count(*) as count'))
    ->groupBy('day')
    ->get()
    ->sortBy(function ($job) {
        return constant('\Carbon\Carbon::'.strtoupper($job->day));
    })
    ->values()
    ->toArray();

or using php > 7.4

$data = DB::table('jobs')
    ->select('day', DB::raw('count(*) as count'))
    ->groupBy('day')
    ->get()
    ->sortBy(fn($job) => constant('\Carbon\Carbon::'.strtoupper($job->day)))
    ->values()
    ->toArray();

This should return them in a Sunday to Saturday order. If you want them ordered Monday to Sunday, you're going to need to tweak it a little.

Instead of

return constant('\Carbon\Carbon::'.strtoupper($job->day))
return (6 + constant('\Carbon\Carbon::'.strtoupper($job->day))) % 7;

Upvotes: 3

HTMHell
HTMHell

Reputation: 6006

In most cases, you probably want to store date data, not a string with the name of the day. That way you can use order by on your date column.

In your case, you can do something like:

$days = array_flip(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]);

usort($data, function($a, $b) use ($days) {
  return $days[$a->day] <=> $days[$b->day];
});

Upvotes: 0

Eloise85
Eloise85

Reputation: 676

You can try simply this :

$outputArray  = array[$data[1],$data[3],...];

Upvotes: -1

Related Questions