获取前几个月的最后几天

Acu*_*ubi 2 php arrays

for($i=0; $i<4; $i++)
{

 $monthArr[] = date("Y-m-d H:i:s", strtotime('2011-10-31'. -1*$i.' month'));

 }
Run Code Online (Sandbox Code Playgroud)

结果:

Array
(
    [0] => 2011-10-31
    [1] => 2011-10-01    //Here should be 2011-09-30
    [2] => 2011-08-31
    [3] => 2011-07-31
)
Run Code Online (Sandbox Code Playgroud)

我希望输出如下,谢谢!

Array
(
    [0] => 2011-10-31
    [1] => 2011-09-30
    [2] => 2011-08-31
    [3] => 2011-07-31
)
Run Code Online (Sandbox Code Playgroud)

liq*_*car 6

strtotime('2011-10-31 -1 month');
Run Code Online (Sandbox Code Playgroud)

这相当于2011-09-31,它不存在,因此它改为2011-09-30之后的第二天,即2011-10-01.

而不是遍历该月的最后一天(这是可变的),尝试循环该月的第一天,然后计算该月的最后一天,即

date( 'Y-m-t', strtotime('2011-10-01 '. -1*$i .' month') );
Run Code Online (Sandbox Code Playgroud)

编辑:date()函数的"t"标志返回该月的最后一天.