我想在我的网站上添加一些文字,说明商店是否根据营业时间开放。如果商店是开放的,它会说直到它开放。如果它没有打开,它会在下一次打开时说明。
我已将开放时间存储在以下变量中:
$opening_times = [
'Monday' => ['09:00' => '17:00'],
'Tuesday' => ['09:00' => '17:00'],
'Wednesday' => ['09:00' => '12:00'],
'Thursday' => ['09:00' => '17:00'],
'Friday' => ['09:00' => '17:00'],
'Saturday' => ['09:30' => '17:00']
];
商店周日休息。
请有人指导我如何做到这一点?我已经看过this example,但我不确定如何处理下一个商店开放的时间以及周日该怎么做。
我希望在下次商店开放时显示一些内容,无论是否在同一天。例如,星期六下午5点30分,我希望该商店下周一上午9点开门。
我之前曾尝试将每天的下一个开放日期和时间存储在$opening_times
变量中,但我想知道是否有更优雅的解决方案。
答案 0 :(得分:2)
在此处使用答案:Determine If Business Is Open/Closed Based On Business Hours作为指南。
这考虑了以后的开放,而不是今天开放。
更新:告诉你下次打开的时间。 (未经测试,因为工作服务器使用PHP 5.3 :()
<?php
$storeSchedule = [
'Sun' => [['12:00' => '01:00', '09:00' => '12:00']],
'Mon' => [['09:00' => '12:00']],
'Tue' => [['09:00' => '12:00']],
'Wed' => [['09:00' => '12:00']],
'Thu' => [['09:00' => '12:00'], ['22:50' => '23:00']],
'Fri' => [['09:00' => '12:00']],
'Sat' => [['12:00' => '01:00', '09:00' => '12:00']]
];
// current or user supplied UNIX timestamp
$timestamp = time();
// default status
$open = false;
// Open later at
$openAt = false;
// get current time object
$currentTime = (new DateTime())->setTimestamp($timestamp);
// Current day
$currentDay = date('D', $timestamp);
if(isset($storeSchedule[$currentDay])){
// loop through time ranges for current day
foreach ($storeSchedule[$currentDay] as $key => $dateGroup) {
$startTime = current(array_keys($dateGroup));
$endTime = current(array_values($dateGroup));
// create time objects from start/end times
$startTime = DateTime::createFromFormat('H:i', $startTime);
$endTime = DateTime::createFromFormat('H:i', $endTime);
// check if current time is within a range
if (($startTime < $currentTime) && ($currentTime < $endTime)) {
$open = true;
break;
}elseif($currentTime < $startTime){
// Opening Later
$openAt = $startTime;
}
}
}else{
// Not open because day is not in array
}
if($open){
echo "We are open";
}else{
if($openAt){
echo "We open later at " . $openAt->format('H:i');
}else{
// Get next open
$arrayDays = array_keys($storeSchedule); // Get an array of the days
$arrayTimes = array_values($storeSchedule); // Get an array of times
$dayIndex = array_search($currentDay, $arrayDays); // Find out what day we are in in the array. To see if there are more this week
$nextDay = ($dayIndex + 1) >= count($arrayDays) ? $arrayTimes[0] : $arrayTimes[$dayIndex + 1]; // If there are no more this week, take the first day, else take the next day.
$nextOpenTime = current(array_keys($nextDay)); // Take the first set of times from this day as the start time
$nextOpenDay = $arrayDays[$dayIndex + 1]; // Get the day key name
echo "We are not open";
echo "We open next on " . $nextOpenDay . " at " . $nextOpenTime->format('H:i');
}
}
?>