假设您有一个数组,表示基于PHP的date('w')
开设商店的星期几,例如:
$open = array(1,3,4); // open on mon/wed/thu
$week = array(0,1,2,3,4,5,6); // full week of days according to date('w')
你有当天date('w')
(例如6代表星期六) - 计算下一个开放日之前的天数/步数的最有效方法是什么?
答案 0 :(得分:1)
这是一个简单的方法......只需寻找下一个可用的日子:
$daysUntilOpen=0;
while (!in_array($day, $open))
{
$day=($day+1)%7;
$daysUntilOpen++;
}
如果你正在进行大量的查询,你可以建立一个数组来告诉你每天开放时间的天数,例如
$daysUntilOpenLookup=array();
foreach($week as $day)
{
$daysUntilOpen=0;
while (!in_array($day, $open))
{
$day=($day+1)%7;
$daysUntilOpen++;
}
$daysUntilOpenLookup[$day]=$daysUntilOpen;
}
现在您只需执行此操作即可查找开放时间之前的天数
$daysUntilOpen=$daysUntilOpenLookup[$day];
答案 1 :(得分:1)
对于$open
上的最多七个值,您可以进行简单的线性搜索:
$nextWeekdayOpen = null;
$daysUntilNextOpen = null;
$currentWeekday = date('w');
foreach ($open as $weekday) {
if ($weekday >= $currentWeekday) {
$nextWeekdayOpen = $weekday;
break;
}
}
if (is_null($nextWeekdayOpen) && !empty($open)) {
$nextWeekdayOpen = $open[0];
}
if (!is_null($nextWeekdayOpen)) {
$daysUntilNextOpen = ($nextWeekdayOpen > $currentWeekday) ? $nextWeekdayOpen-$currentWeekday : 6-$currentWeekday+$nextWeekdayOpen;
}
这简单地迭代打开的工作日并查找等于(即今天打开)或大于当前工作日的第一个工作日。如果没有,则需要第一个打开的工作日(假设打开工作日的排序)。最后计算下一个开放工作日和当前工作日之间的天数。
该算法以线性时间复杂度运行。
答案 2 :(得分:1)
我不确定效率是否真的是一个问题,因为少量的项目:
for($i=1;$i<7;$i++) {
if (in_array((($day+$i)%7), $open)) break;
}
echo "Next open day in $i days";
答案 3 :(得分:0)
这是我使用非常有用的strtotime()函数的方式。它的工作方式也非常清楚。
<?php
// Get the current timestamp for comparison
$now = time();
// Get unix timestamps for each open day relative to comparison time $now
$monday = strtotime("next monday", $now);
$tuesday = strtotime("next wednesday", $now);
$thursday = strtotime("next thursday", $now);
// Put values in to array
$days_open = array($monday, $tuesday, $thursday);
// See which unix timestamp is least (the nearest to current day)
$nearest_day = min($days_open);
// Then you can get difference in days
$days_difference = date('w', $nearest_day) - date('w', $now);
// You can show the difference like this
echo "We're next open in " , $days_difference , " days";
?>