【发布时间】:2017-11-30 10:44:33
【问题描述】:
我正在开发一个网站,用户可以在该网站上每 X 天创建一些事件(其中 X 是一周中某一天的名称)。然后,他需要输入他想在未来创建的事件数。
例如,用户选择每周一和周二,并决定创建 150 个事件。
这是我到目前为止所做的代码:
// Init the date counter
$cpt_date_found = 0;
// Number of date to find
$rec_occ = 150;
// Init an ending date far in the future
$endDate = strtotime('+10 years', time());
// Loop over the weeks
for($i = strtotime('Monday', strtotime(date("d.m.Y"))); $i <= $endDate; $i = strtotime('+1 week', $i)) {
// -- Monday date found, create the event in the database
$cpt_date_found++;
// Break the loop if we have enough dates found
if($cpt_date_found == $rec_occ) {
break;
}
}
此代码查找未来每个星期一的日期,并在达到用户指定的出现次数后中断循环。
我输入了一个远在未来的结束日期,以确保我可以在用户指定的出现次数结束之前中断循环。
首先,我不确定我的代码的“质量”...我知道打破循环不是最好的主意,我想知道另一种解决方案是否更适合我的需求。
那么,如果用户指定了几天(比方说,星期一、星期二和星期五),而不是重复循环更多次,有没有办法为每个提供的日期循环一次?
谢谢!
【问题讨论】:
-
stackoverflow.com/a/33329004/8165478 这个答案应该做你想做的。
标签: php date calendar recurrence