Fahad Sohail
Fahad Sohail

Reputation: 1846

12 Hour Clock Array Sort

I have been searching on Google and couldn't find any solution to sort an array according to the 12 Hour clock format. I was able to sort the 24 hour clock by converting it to timestamps and then using krsort. But I am not sure how to sort a 12 Hour Clock ..

Following would be the example of the scenario ..

Unsorted

array(
    '0' => '03:00 AM',
    '1' => '12:00 AM',
    '2' => '03:00 PM',
    '3' => '01:00 AM',
    '4' => '04:00 PM',
    '5' => '02:00 AM',
    '6' => '12:00 PM',
    '7' => '04:00 AM',
    '8' => '01:00 PM',
    '9' => '02:00 PM'
);

Sorted

array(
    '0' => '12:00 AM',
    '1' => '01:00 AM',
    '2' => '02:00 AM',
    '3' => '03:00 AM',
    '4' => '04:00 AM',
    '5' => '12:00 PM',
    '6' => '01:00 PM',
    '7' => '02:00 PM',
    '8' => '03:00 PM',
    '9' => '04:00 PM'
);

The code obviously would work dynamically, so what ever time is given in the array it will be sorted to a 12 Hour Clock in ascending order or descending order

Upvotes: 2

Views: 1548

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

strtotime will accept that format. So you can use a custom sort (usort) with a strtotime based callback.

usort($array, function($a, $b) {
   return (strtotime($a) > strtotime($b));
});

Upvotes: 3

Related Questions