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

时间:2021-02-08 05:31:11

直接上代码:

             $time=array();
$currentTime = time();
$cyear = floor(date("Y",$currentTime));
$cMonth = floor(date("m",$currentTime));
for($i=0;$i<12;$i++){
$nMonth = $cMonth-$i;
$cyear = $nMonth == 0 ? ($cyear-1) : $cyear;
$nMonth = $nMonth <= 0 ? 12+$nMonth : $nMonth;
$time[]['time']=$cyear.$nMonth;
}

结果:

 array(12) {
[0] => array(1) {
["time"] => string(5) "20194"
}
[1] => array(1) {
["time"] => string(5) "20193"
}
[2] => array(1) {
["time"] => string(5) "20192"
}
[3] => array(1) {
["time"] => string(5) "20191"
}
[4] => array(1) {
["time"] => string(6) "201812"
}
[5] => array(1) {
["time"] => string(6) "201811"
}
[6] => array(1) {
["time"] => string(6) "201810"
}
[7] => array(1) {
["time"] => string(5) "20189"
}
[8] => array(1) {
["time"] => string(5) "20188"
}
[9] => array(1) {
["time"] => string(5) "20187"
}
[10] => array(1) {
["time"] => string(5) "20186"
}
[11] => array(1) {
["time"] => string(5) "20185"
}
}