我正在从事一个PHP项目,我需要计算企业的营业时间,其中包括每周定期安排和特殊的非标准假期时间.我有两个数组:一个用于常规日程,另一个用于非标准时间.
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']
];
利用this question的一些灵感,我能够为非标准的开放时间数组制作这个:
// 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;
这似乎如预期的那样工作,但我仍然需要从每周开放时间中找到下一个最近的开放日期和时间,而且我完全不知道该如何做到.有人能提供一些线索吗?谢谢.