osakagreg
osakagreg

Reputation: 577

sort array based on 12-hour customized clock

My array is as follows:

Array ( [01:00 pm] => Lunch [03:00 pm] => Dance [12:45 pm] => Guests arrive [12:50 pm] => Find seats [12:55 pm] => Blessing )

I need to convert these keys to a customized time format for sorting so that a correct order would look like this:

Array ( [12:45 pm] => Guests arrive [12:50 pm] => Find seats [12:55 pm] => Blessing [01:00 pm] => Lunch  [03:00 pm] => Dance )

But that's not all. These parties often end at 1am or 2am in the morning. Therefore it would make sense to start the clock with 3am being the first value. As such, a 02:00 am entry would appear at the end of the sorted list and a 05:00 am entry would appear at the very beginning (because I want to designate 03:00 am as the beginning of the clock.

If I had a 02:00 am and 05:00 am example in the array, it would read as:

Array ( [05:00 am] => Wake up [12:45 pm] => Guests arrive [12:50 pm] => Find seats [12:55 pm] => Blessing [01:00 pm] => Lunch  [03:00 pm] => Dance [02:00 am] => Party ends)

I don't know where or how to transform the keys from the array. I currently have:

 ksort($event_order);
                foreach ( $event_order as $time => $event) {
                    echo '<div><strong>';
                    echo $time;
                    echo '</strong> - ';
                    echo $event;
                    echo '</div>';
                }

Upvotes: 0

Views: 229

Answers (1)

trincot
trincot

Reputation: 350477

Here is one way of doing it, using array_multisort, mapping the times strings to number of seconds since midnight, and moving the first 3 hours to the end:

$event_order = Array ( 
    "12:45 pm" => "Guests arrive",
    "12:55 pm" => "Blessing",
    "02:00 am" => "Party ends",
    "05:00 am" => "Wake up",
    "01:00 pm" => "Lunch",
    "03:00 pm" => "Dance",
    "12:50 pm" => "Find seats");

array_multisort(array_map(function ($v) {
    return (strtotime($v) - strtotime("midnight") + 21*3600) % (24*3600);
}, array_keys($event_order)), $event_order);

print_r($event_order);

Upvotes: 2

Related Questions