我想获取一个时期内的日期数组。为此,我想到了一个for循环(似乎很简单...),但是即使运行日期为1个月,它也会超时。
这是我的PHP:
$startdate = '2018-01-31';
$recurring = '2';
switch($recurring) {
case '1':
$period = '+1 day';
break;
case '2':
$period = '+1 week';
break;
case '3':
$period = '+1 month';
break;
case '4':
$period = '+3 months';
break;
case '5':
$perion = '+1 year';
break;
default:
$period = null;
break;
}
$dates = [];
if($period !== null) {
for($date = $startdate; $date < strtotime('+1 month', $startdate); strtotime($period, $date)) {
$dates[] = $date;
}
}
echo json_encode($dates);
增加$date
与$date = strtotime($period, $date)
在for循环的增量部分应保持其超时,但也有几个可能进行其他方面的改进。
首先,我建议您在循环之前计算您的结束日期,以避免strtotime
每次检查继续条件时都需要额外的电话。
$end = strtotime("$startdate +1 month");
然后,$date = strtotime($startdate)
在初始化部分进行设置,否则将获得日期字符串而不是时间戳作为$dates
数组中的第一个值。
for ($date = strtotime($startdate); $date < $end; $date = strtotime($period, $date)) {
$dates[] = $date;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句