You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

根据用户选择的起止日期生成年月数组的技术实现需求

生成指定日期范围的年月数组解决方案

这里有一个实用的PHP函数,能够完美匹配你需要的年月数组生成需求:

function generateMonthRange($yearFrom, $monthFrom, $yearTo, $monthTo) {
    // 将输入的年月转换为DateTime对象,方便日期操作
    $startDate = DateTime::createFromFormat('Y-n', "$yearFrom-$monthFrom");
    $endDate = DateTime::createFromFormat('Y-n', "$yearTo-$monthTo");
    
    $monthList = [];

    // 循环遍历从起始到结束的每个月份
    while ($startDate <= $endDate) {
        $monthList[] = [
            'year' => $startDate->format('Y'),
            'month' => $startDate->format('n') // 输出不带前导零的月份,如"1"而非"01"
        ];
        
        // 将日期向后推移一个月
        $startDate->modify('+1 month');
    }

    return $monthList;
}

// 你的请求参数示例
$yearFrom = "2016";
$monthFrom = "12";
$yearTo = "2017";
$monthTo = "5";

// 生成结果数组
$result = generateMonthRange($yearFrom, $monthFrom, $yearTo, $monthTo);
print_r($result);

代码逻辑说明

  • 日期对象转换:使用DateTime::createFromFormat把字符串格式的年月转换成可操作的日期对象,自动处理年份和月份的进位问题(比如从12月到次年1月的跨年逻辑),不用手动写复杂的判断。
  • 循环遍历:通过while循环逐个遍历每个月份,只要当前日期不超过结束日期,就将该年月的信息存入结果数组。
  • 月份格式控制:用format('n')获取不带前导零的月份数字,完全匹配你期望的数组格式;如果需要带前导零的月份,只需把'n'改成'm'即可。
  • 边界兼容:这个函数能处理各种边界情况,比如起始年月和结束年月相同、跨多个年份的大范围等。

运行这段代码后,你会得到和示例完全一致的输出结果。

内容的提问来源于stack exchange,提问作者RAVI BANGKIT NUR ZIKRILLAH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:45:52