问题:获取n年前当月到今年当月的所有月份。
例如: 2014年8月到2019年8月间的所有月份。
<?php
/**
* 需求:获取 n 年前当月到现在当月的所有月份
* 思路:采用循环,递减月份到 n 年前的当月
* 思路:n年共 12n 个月,但考虑到 n年前的当月 也算一次记录,所以一共 12n+1 次循环
*
* @param int $n 多少年前
* @return array
*/
function getMonthsInTime (int $n) {
$num = $n * 12;
$res = [];
for($i=$num; $i>=0; $i--){
$res[] = date("Y-m", strtotime("-{$i} month"));
}
return $res;
}
$res = getMonthsInTime(5);
echo '<pre>';
print_r($res);
// 运行结果
Array
(
[0] => 2014-08
[1] => 2014-09
[2] => 2014-10
[3] => 2014-11
[4] => 2014-12
[5] => 2015-01
[6] => 2015-02
[7] => 2015-03
[8] => 2015-04
[9] => 2015-05
[10] => 2015-06
[11] => 2015-07
[12] => 2015-08
[13] => 2015-09
[14] => 2015-10
[15] => 2015-11
[16] => 2015-12
[17] => 2016-01
[18] => 2016-02
[19] => 2016-03
[20] => 2016-04
[21] => 2016-05
[22] => 2016-06
[23] => 2016-07
[24] => 2016-08
[25] => 2016-09
[26] => 2016-10
[27] => 2016-11
[28] => 2016-12
[29] => 2017-01
[30] => 2017-02
[31] => 2017-03
[32] => 2017-04
[33] => 2017-05
[34] => 2017-06
[35] => 2017-07
[36] => 2017-08
[37] => 2017-09
[38] => 2017-10
[39] => 2017-11
[40] => 2017-12
[41] => 2018-01
[42] => 2018-02
[43] => 2018-03
[44] => 2018-04
[45] => 2018-05
[46] => 2018-06
[47] => 2018-07
[48] => 2018-08
[49] => 2018-09
[50] => 2018-10
[51] => 2018-11
[52] => 2018-12
[53] => 2019-01
[54] => 2019-02
[55] => 2019-03
[56] => 2019-04
[57] => 2019-05
[58] => 2019-06
[59] => 2019-07
[60] => 2019-08
)
网友评论