One way to deal with your year issue is to compare $vBillMonthPrev
with the current month, and if it is greater than that, supplying a year
parameter to mktime
which is for the previous year. Then you can make a DateTime
object from that date, and subtract one month in a loop to generate values into your $m_array
. Note that it is preferable to subtract a month at a time rather than making a new date variable, as this will correctly deal with the case where the month underflows into the previous year.
$vBillMonthPrev = '11';
$vBillYearPrev = (int)date('Y') - ((int)$vBillMonthPrev > (int)date('n') ? 1 : 0);
$date = date_create_from_format('U', mktime(0, 0, 0, $vBillMonthPrev, 15, $vBillYearPrev));
$m_array = array();
for ($i = 1; $i < 7; $i++) {
$date->modify('-1 month');
$m_array[] = $date->format('M-y');
}
print_r($m_array);
Output:
Array
(
[0] => Oct-20
[1] => Sep-20
[2] => Aug-20
[3] => Jul-20
[4] => Jun-20
[5] => May-20
)
Demo on 3v4l.org
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…