PHP生成当前月份包括最近12个月内的月份

1.倒序方法:

 1             $time=array();
 2             $currentTime = time();
 3             $cyear = floor(date("Y",$currentTime));
 4             $cMonth = floor(date("m",$currentTime));
 5             for($i=0;$i<12;$i++){
 6                 $nMonth = $cMonth-$i;
 7                 $cyear = $nMonth == 0 ? ($cyear-1) : $cyear;
 8                 $nMonth = $nMonth <= 0 ? 12+$nMonth : $nMonth;
 9                 $time[]['time']=$cyear.$nMonth;
10             }

结果:

 1 array(12) {
 2   [0] => array(1) {
 3     ["time"] => string(5) "20194"
 4   }
 5   [1] => array(1) {
 6     ["time"] => string(5) "20193"
 7   }
 8   [2] => array(1) {
 9     ["time"] => string(5) "20192"
10   }
11   [3] => array(1) {
12     ["time"] => string(5) "20191"
13   }
14   [4] => array(1) {
15     ["time"] => string(6) "201812"
16   }
17   [5] => array(1) {
18     ["time"] => string(6) "201811"
19   }
20   [6] => array(1) {
21     ["time"] => string(6) "201810"
22   }
23   [7] => array(1) {
24     ["time"] => string(5) "20189"
25   }
26   [8] => array(1) {
27     ["time"] => string(5) "20188"
28   }
29   [9] => array(1) {
30     ["time"] => string(5) "20187"
31   }
32   [10] => array(1) {
33     ["time"] => string(5) "20186"
34   }
35   [11] => array(1) {
36     ["time"] => string(5) "20185"
37   }
38 }

 

2.顺序方法

1   $today = input('param.today') ? input('param.today') : date("Y-m-d");
2         $arr = array();
3         $old_time = strtotime('-5 month',strtotime($today));
4         for($i = 0;$i < 6; ++$i){
5             $t = strtotime("+$i month",$old_time);
6             $arr[]=date('Y-m',$t);
7         }

结果:

Array
(
    [0] => Array
        (
            [time] => 2020-04
        )

    [1] => Array
        (
            [time] => 2020-05
        )

    [2] => Array
        (
            [time] => 2020-06
        )

    [3] => Array
        (
            [time] => 2020-07
        )

    [4] => Array
        (
            [time] => 2020-08
        )

    [5] => Array
        (
            [time] => 2020-09
        )

)

 

posted @ 2019-04-29 09:37  原来是个帅小伙  阅读(1422)  评论(0编辑  收藏  举报