I’m working on a PHP project where I need to calculate the opening times for a business, which includes both regular weekly schedules and special non-standard times for holidays. I have two arrays: one for the regular schedule and another for the non-standard times.
Regular opening times array:
$opening_times = [
['open' => '09:00:00', 'weekday' => 1], // Monday
['open' => '09:00:00', 'weekday' => 2], // Tuesday
['open' => '09:00:00', 'weekday' => 4], // Thursday, Wednesday is closed
['open' => '09:00:00', 'weekday' => 5], // Friday opening time 1
['open' => '16:00:00', 'weekday' => 5], // Friday opening time 2
['open' => '09:00:00', 'weekday' => 6], // Saturday
['open' => '09:00:00', 'weekday' => 7], // Sunday
];
Non-standard opening times array (for holidays etc.):
$special_opening_times = [
['date' => '2024-04-24', 'open' => '08:00:00'],
['date' => '2024-04-27', 'open' => '08:00:00'],
['date' => '2024-04-28', 'open' => '09:00:00'],
['date' => '2024-04-30', 'open' => '07:00:00'],
['date' => '2024-04-25', 'open' => '11:00:00']
];
Using some inspiration from this question I was able to craft this for the non-standard opening times array:
// Your reference datetime
$reference_datetime = '2024-04-25 10:30:00';
// Array with dates and times
$special_opening_times = [
['date' => '2024-04-24', 'open' => '08:00:00'],
['date' => '2024-04-27', 'open' => '08:00:00'],
['date' => '2024-04-28', 'open' => '09:00:00'],
['date' => '2024-04-30', 'open' => '07:00:00'],
['date' => '2024-04-25', 'open' => '11:00:00'] // Same day, later time
];
// Function to sort datetimes
function datetime_sort($a, $b) {
$a_datetime = strtotime($a['date'] . ' ' . $a['open']);
$b_datetime = strtotime($b['date'] . ' ' . $b['open']);
return $a_datetime - $b_datetime;
}
// Sort datetimes using the custom function
usort($special_opening_times, 'datetime_sort');
// Variable to hold the next closest datetime
$next_datetime = null;
// Loop through sorted datetimes and find the next closest datetime
foreach ($special_opening_times as $date_array) {
$current_datetime = strtotime($date_array['date'] . ' ' . $date_array['open']);
if (strtotime($reference_datetime) < $current_datetime) {
$next_datetime = $date_array['date'] . ' ' . $date_array['open'];
break;
}
}
// Output the next closest datetime
echo $next_datetime;
Which seems to work as expected, however I still need to find the next closest opening date and time from the weekly opening hours, and I’m at a total loss on how to do it. Could anyone shed some light. Thanks.