如何列出最近12个月


How to list last 12 months

我想列出从今天开始的12个月。还有几个月的时间……

$i = 12;
while ($i > 0) {
    $ym = date('Y-m', strtotime("-$i month"));
    $yms [$ym] = $ym;
    $i--;
}
print_r($yms);

在线示例:http://codepad.org/XDv4iR3u

您忘记在strtotime中提供当前的ym。考虑这个例子:

$yms = array();
$now = date('Y-m');
for($x = 12; $x >= 1; $x--) {
    $ym = date('Y-m', strtotime($now . " -$x month"));
    $yms[$ym] = $ym;
}
echo "<pre>";
print_r($yms);
echo "</pre>";
样本输出:

Array
(
    [2013-05] => 2013-05
    [2013-06] => 2013-06
    [2013-07] => 2013-07
    [2013-08] => 2013-08
    [2013-09] => 2013-09
    [2013-10] => 2013-10
    [2013-11] => 2013-11
    [2013-12] => 2013-12
    [2014-01] => 2014-01
    [2014-02] => 2014-02
    [2014-03] => 2014-03
    [2014-04] => 2014-04
)

使用日期时间和日期间隔

<?php
$t = new Datetime();
$interval = new DateInterval("P1M");
for($i=0;$i<12;$i++){
    echo $t->sub($interval)->format('Y-m')."'n";
}
https://ideone.com/oQ0FRO

您需要明确地从当前月初开始。因为我们现在是31号,你会错过任何少于31天的月份。

<?php
$i = 12;
while ($i > 0) {
    $ym = @date('Y-m', strtotime(date('Y-m-01') . " -$i month"));
    $yms [$ym] = $ym;
    $i--;
}
print_r($yms);
?>