Reputation: 527
I have an event calendar where I'm usorting the events pulled back from the database. However the midnight items are technically earlier programmatically so they are showing up first in the list. How can I sort so that items midnight and later will show up at the end of the list?
usort($events, function($a, $b) {
//if after midnight (before 8am of next day)
return strtotime($a['start_time']) >= strtotime('8:00') ? strtotime($a['start_time']) - strtotime($b['start_time']) : 1;
});
The way I have it now, they're sorting in the right order but the midnight or later items are showing up just after the first item. If I sort it normally without this "before 8am condition" they show up first.
Upvotes: 1
Views: 81
Reputation: 781503
If the time is in the early morning, add a day to it so it will be after evening times.
usort($events, function($a, $b) {
$oneday = 86400; // seconds in a day
$cutoff = strtotime('8:00');
$atime = strtotime($a['start_time']);
if ($atime < $cutoff) {
$atime += $oneday;
}
$btime = strtotime($b['start_time']);
if ($btime < $cutoff) {
$btime += $oneday;
}
return $atime - $btime;
});
Upvotes: 1