如何在php中显示最近10个月的列表?

时间:2016-07-12 09:14:52

标签: php arrays

我想在我的项目中显示当月的last 10 month。我试过这个

    <?php
$months = array();
for ($i=1; $i<11; $i++) {
 $months[$i."_".date('Y', strtotime('-'.$i.' Month'))] = date('M', strtotime('-'.$i.' Month'));
}

它给了我

   Array
(
    [1_2016] => Jun
    [2_2016] => May
    [3_2016] => Apr
    [4_2016] => Mar
    [5_2016] => Feb
    [6_2016] => Jan
    [7_2015] => Dec
    [8_2015] => Nov
    [9_2015] => Oct
    [10_2015] => Sep
)

index month没错,我想要这个

Array
(
    [6_2016] => Jun
    [5_2016] => May
    [4_2016] => Apr
    [3_2016] => Mar
    [2_2016] => Feb
    [1_2016] => Jan
    [12_2015] => Dec
    [11_2015] => Nov
    [10_2015] => Oct
    [9_2015] => Sep
)

请帮助任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:2)

而不是$i

$months[$i."_".

您需要像{/ p>一样使用date功能

$months[date('n',strtotime('-'.$i.' Month'))."_"

答案 1 :(得分:2)

我认为这就是你想要的

$dateArray = array();
for ($i=1; $i<=10; $i++) { 
    $dateArray[date('m_Y', strtotime("-$i month"))] = date('M', strtotime("-$i month"));
} 
print_r($dateArray);

<强>输出

Array
(
    [06_2016] => Jun
    [05_2016] => May
    [04_2016] => Apr
    [03_2016] => Mar
    [02_2016] => Feb
    [01_2016] => Jan
    [12_2015] => Dec
    [11_2015] => Nov
    [10_2015] => Oct
    [09_2015] => Sep
)

答案 2 :(得分:1)

只需使用日期格式和月减法的strtotime

$months = array();
for ($i=1; $i<11; $i++) {
 $months[date('n_Y', strtotime('-'.$i.' Month'))] = date('M_Y', strtotime('-'.$i.' Month'));
}
var_dump($months);

日期格式

  

Y - 一年的四位数表示

     

n - 月份的数字表示,不带前导零(1到12)

     

M - 一个月的短文本表示(三个字母)