一、代码

<script>
    let months = getLastAllMonthByNumber(6, '2021-07');
    console.log(months);

    /**
     * 打印
     * Array(6) [ "2021-02", "2021-03", "2021-04", "2021-05", "2021-06", "2021-07" ]
     */

    //获取当前月的前N个月的所有月份数据,月份从小到大
    function getLastAllMonthByNumber(number, time) {
        let months = [time]; //最后一个月是传过来的当前月
        for (let i = 0; i < (number-1); i++) {
            let firstDate = months[0] + '-01 00:00:00'; //月份的第一天
            let lastUnix = dateToUnix(firstDate) - 1; //当月第一天的时间戳-1s,得到上个月时间戳
            let lastMonth = unixToDate(lastUnix, "YYYY-MM"); //根据上个月时间戳,直接获取上个月日期(默认返回YYYY-MM-DD H:m:s格式)
            months.unshift(lastMonth); //追加到已有月份的前面
        }
        return months; //返回结果数据
    }

    //日期格式转时间戳:返回日期对应的(10位数)时间戳
    function dateToUnix(datetime) {
        let tmp_datetime = datetime.replace(/:/g,'-');
        tmp_datetime = tmp_datetime.replace(/ /g,'-');
        let arr = tmp_datetime.split("-");
        let now = new Date(Date.UTC(arr[0], arr[1]-1, arr[2], arr[3]-8, arr[4], arr[5]));
        return parseInt((now.getTime()) / 1000);
    }

    //时间戳转日期格式:默认返回YYYY-MM-DD H:m:s格式的日期数据
    function unixToDate(unix, formatStr) {
        let date = new Date(parseInt(unix) * 1000);
        let Y = date.getFullYear();
        let M = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
        let D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate();
        let h = date.getHours();
        let m = date.getMinutes();
        let s = date.getSeconds();
        formatStr = formatStr || 'YYYY-MM-DD H:m:s';
        return formatStr.replace(/YYYY|MM|DD|H|m|s/ig, function (matches) {
            return ({
                YYYY: Y,
                MM: M,
                DD: D,
                H: h,
                m: m,
                s: s
            })[matches];
        });
    }
</script>

二、对应的PHP方法