i have time slots like
$timeslot = ['09:00-10:00', .... '23:00-00:00', '00:00-01:00'];
I have records with updated time as 23:15:00
, 23:30:00
, 00:15:00
, 09:15:00
etc.
What i’m trying to find is the sum of records between each of the $timeslot
. I’m not considering what day got updated, only time i’m looking for.
i tried with:-
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00']; foreach($data as $val) { $cnt = 0; foreach($timeslot as $slots) { $slot = explode("-", $slots); if( (strtotime($val) > strtotime($slot[0])) && (strtotime($val) <= strtotime($slot[1])) ) { $up_time[$slot[0] . '-' . $slot[1]] = $cnt++; } } } echo '<pre>';print_r($up_time);echo '</pre>';
The expected output is:-
09:00-10:00 = 1 23:00-00:00 = 2 00:00-01:00 = 1
Advertisement
Answer
Strtotime is not required since your time can be compared as strings.
This code works as you expected.
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00']; $timeslot = ['09:00-10:00', '23:00-00:00', '00:00-01:00']; $up_time = array(); foreach ($data as $val) { $myTime = substr($val, 0, 5); foreach ($timeslot as $slot) { $times = explode("-", $slot); if (substr($times[1], 0, 3) == "00:") { $times[1] = "24:" . substr($times[1], 3); } if ($myTime >= $times[0] && $myTime <= $times[1]) { if (!isset($up_time[$slot])) { $up_time[$slot] = 1; } else { $up_time[$slot]++; } } } } echo '<pre>'; print_r($up_time); echo '</pre>';
The if with ‘substr’ is needed because for midnight you have ’00’ and not ’24’ so the computer thinks is an empty set (such as hours bigger then 23 and smaller then 0).
Comparison is made between string because bigger time is also a bigger string since you use 2 digits for hours.
You need to count equal slots so you need an array with an element for each slot and increment if duplicate or create an element if not found (the condition ‘!isset’).
Update for modification request
$data = ['23:15:00', '23:30:00', '00:15:00', '09:15:00']; // added unused slot 8:00-9:00 $timeslot = ['08:00-09:00','09:00-10:00', '23:00-00:00', '00:00-01:00']; $up_time = array(); // new initialization foreach ($timeslot as $slot) { $up_time[$slot] = 0; } foreach ($data as $val) { $myTime = substr($val, 0, 5); foreach ($timeslot as $slot) { $times = explode("-", $slot); if (substr($times[1], 0, 3) == "00:") { $times[1] = "24:" . substr($times[1], 3); } if ($myTime >= $times[0] && $myTime <= $times[1]) { $up_time[$slot]++; // simplified } } }