Reorder A Numerically Keyed Array Using Array Splice?
So today I was given an interesting task by a client. I had the output of a certain function. That function returns an array containing the days of the week (via numeric key, 0 = Sunday, 1 = Monday, etc). The value of each key was an array containing data. Something like this:
1 2 3 4 5 6 |
[ 2 => [] 4 => [] 1 => [] ... ] |
Using shorthand array syntax here & just using [] to represent the object of data each array item contained. Oh and as you may have noticed, while a day was never repeated (it only ever contained 7 items) they were never in the correct order. Also note I didn’t have access to the MySQL query to reorder the data as it came in.
To keep things easy to understand they wanted to list out the data grouped by day and list the days from Today onward. So if today was Wednesday (which it is), it would look like:
- Wednesday
- Thursday
- Friday
- Saturday
- Sunday
- Monday
- Tuesday
Then tomorrow Thursday would be at the top & Wednesday would be pushed to the end… Get the idea. So how do you do that? Well that’s a question I asked myself.
I ended using only a small section of code, but I thought it might be interesting to share.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//Get weekday index. $today = date('w', time()); //Day indices with their textual values for output $days = [0 => 'Sunday', 1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday']; //Sort results ksort($data); //Replace Today with 'Today' $days[$today] = 'Today'; //If today isn't Sunday slice array into correct order if($today != 0) { //Get days from today onward $tafter = array_slice($data, $today, null, true); //Get from Sunday to today (not inclusive) $before = array_slice($data, 0, $today, true); //Union $data = $tafter + $before; } //Do what you will with $data |
This is what I settled upon and the client is very happy with the results, but I’m curious as to if there are any easier or more compact ways to do this. The important things were that all the array data is left intact, the array keys are preserved and that it be in the order shown but change each day automatically.
Let me know how you would have done it, I’d love to see how many lines it can be brought down to.
Also don’t forget to visit my new personal blog to keep up-to-date with when new tutorials are incoming and other quirky things from the daily thoughts of a crazy person web developer.
3 Comments
Salih
Hi,
Waiting for the Third Part of ‘CREATING A SIMPLE WEBSITE USING SENSIOLABS (SYMFONY) SILEX AND TWIG’.
Paul Robinson
Hi Salih,
The third part will be coming very soon. I’ll try to get it posted in the next few days (probably the weekend).
Paul Robinson
Hi Salih,
Sorry for the delay with this, work has been pretty heavy as it has come up to Christmas. Here is the long awaited 3rd part of this tutorial.
http://return-true.com/2014/12/simple-website-silex-twig-adding-form-validation/