每年每个月的php - for循环 [英] php - for loop for each month of year

查看:93
本文介绍了每年每个月的php - for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个循环,检查当前月份,未来12个月和过去4个月。

I want a loop that checks the current month, 12 months in the future and 4 months in the past.

例如:今天是8月1日08.我的四月,五月,六月,七月,八月,九月,十月,十一月,十二月,一月,二月,三月,四月,五月,六月,七月和八月。

For example: Today is 1st August 08. My loop should go through April, May, June, July, August, September, October, November, December, January, February, March, April, May, June, July, and August.

我尝试过时间,但我不知道我将来可以如何循环4个月,12个月。

I have tried strotime but I don't know how I can loop 4 months back and 12 months in the future.

这是我的代码

$i = 1; 
$month = strtotime('2013-08-01');

    while($i <= 12) {
        $month_name = date('F', $month);
        echo $month_name;
        echo "<br>";

        $month = strtotime('+1 month', $month);
        $i++;


推荐答案

我认为Yoshi几乎在那里,这是答案,但使用 DatePeriod DateTime 更加一致,并使更易读的代码IMHO: -

I think Yoshi was almost there with his answer, but using DatePeriod with DateTime is more consistent and makes for more readable code IMHO:-

$oneMonth = new \DateInterval('P1M');
$startDate = \DateTime::createFromFormat('d H:i:s', '1 00:00:00')->sub(new \DateInterval('P4M'));
$period = new \DatePeriod($startDate, $oneMonth, 16);

foreach($period as $date){
    //$date is an instance of \DateTime. I'm just var_dumping it for illustration
    var_dump($date);
}

看到它工作

这篇关于每年每个月的php - for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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