0

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.

1
  • Please include your code as text not as an image Commented Feb 6, 2021 at 14:36

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for including the second way of doing it. It worked out perfectly and I was able to sort from Monday to Sunday!
0

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

Comments

-1

You can try simply this :

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

2 Comments

This fails if result doesn't have all days (i.e. if there is no some of day in table rows).
Also fails for other cases where given data is sorted differently, this answer is usable only for a very specific case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.