PHP循环通过日期 [英] PHP Looping through dates

查看:129
本文介绍了PHP循环通过日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下while循环,比较2个日期,以查看1是否小于另一个,如果不是,则在第一个日期添加一个星期。



它工作正常,但是如果日期之间有更大的差异(即大于12个月),我会收到超时错误,因为它已经过最大执行时间。



任何人都可以帮助我提高效率?

  while($ startDate-> timestamp< $ current_week-> timestamp) {
$ data ['weeks'] [$ w] = array(
'monday'=> $ startDate-> startofWeek() - > format('d / m / Y' ,
'sunday'=> $ startDate-> endofWeek() - > format('d / m / Y')
);
$ w ++;
$ startDate = $ startDate-> addDays(7); //将其移动到下一周
}

我应该补充说,我是使用DateTime的Carbon API扩展程序



感谢



----编辑----

发生了一些奇怪的事情,我不明白。如果我把硬编码的日期传递给$ startDate,那么2013-01-06之后的所有内容都可以正常运行(快速),但是在这个日期之后,它会一直超时。任何想法任何人?

解决方案

看起来你还在做一点更多的 $ startDate 您正在使用 - > startOfWeek() - > endOfWeek()而不是只计算字符串输出;我阅读了 Carbon 的资料来源是每种方法你调用修改对象,所以在while循环的最后一行中的赋值是不必要的(它可以很容易地写成$ code> $ startDate-> addDays(7);

然而,我怀疑这个代码块不是你真正的问题,而且你的代码库进一步下降 - 如果你的问题随着$ data ['weeks']的大小而增长,那么这可能是你正在处理的方式它为您的HTML。


I have the following while loop which compares 2 dates to see if 1 is less than another, and if not then it adds a week to the first date.

It works fine, however where there is a greater difference between the dates (i.e. greater than 12 months) I get a timeout error as it has passed the max execution time.

Can anyone help me make this more efficient?

        while($startDate->timestamp < $current_week->timestamp){
            $data['weeks'][$w] = array(
                'monday' => $startDate->startofWeek()->format('d/m/Y'), 
                'sunday' => $startDate->endofWeek()->format('d/m/Y')
            );
            $w++;
            $startDate = $startDate->addDays(7); // Move it on to the following week
        }

I should add that I'm working with the Carbon API extension for DateTime

Thanks

----Edit----

Something strange is happening that I don't understand. If I pass a date hard coded to $startDate everything after 2013-01-06 works fine (and fast) but as soon as goes after this date it times out. Any ideas anyone?

解决方案

It looks like you're doing a little more to $startDate than you expect - you're modifying the object with ->startOfWeek() and ->endOfWeek() rather than just calculating the string output; my reading of the source to Carbon is that every method you call modifies the object, so the assignment in the last line of your while loop is unnecessary (it could just as easily be written as $startDate->addDays(7);. As a result of that your code is a little bit less efficient than it could be, and might even loop one or two times more than you want.

However, I would suspect this block of code isn't your real problem, and that it's further down your codebase - if your problems grow with the size of $data['weeks'] then it's probably something in the way in which you're processing it for your HTML.

这篇关于PHP循环通过日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆