【问题标题】:php timeout on for loop with dates带有日期的for循环的php超时
【发布时间】:2018-08-09 20:53:08
【问题描述】:

我想获得一个时期内的日期数组。为此,我想出了一个 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
  • strtotime($period, $date) $period 有增量
  • 查看strtotime 的文档。它是否修改了作为第二个参数传递的时间戳?
  • 对……它没有(当然)。知道如何解决这个问题吗?
  • 我找到了.. 将 strtotime($period, $date) 更改为 $date = strtotime($period, $date) 成功了。谢谢! @不要恐慌

标签: php date for-loop timeout


【解决方案1】:

在 for 循环的增量部分增加 $date$date = strtotime($period, $date) 应该可以防止它超时,但是还有一些其他的改进可以做。

首先,我建议在循环之前计算一次结束日期,以避免在每次检查延续条件时额外调用strtotime

$end = strtotime("$startdate +1 month");

然后,在初始化部分设置$date = strtotime($startdate),否则您将获得日期字符串而不是时间戳作为$dates 数组中的第一个值。

for ($date = strtotime($startdate); $date < $end; $date = strtotime($period, $date)) {
    $dates[] = $date;
}

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多