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

如何使用PHP获取年份相关的月份列表并存入数组

获取关联年份的月份列表并存入数组实现

基础中文月份静态数组

如果仅需要固定的中文月份名称列表,可直接使用以下定义:

$months = [
    '一月',
    '二月',
    '三月',
    '四月',
    '五月',
    '六月',
    '七月',
    '八月',
    '九月',
    '十月',
    '十一月',
    '十二月'
];

关联年份的动态月份数组

如果需要月份和指定年份绑定,同时获取对应月份的天数等关联属性,可使用以下封装方法:

function getLinkedMonthList(int $targetYear): array
{
    // 中文月份名称映射
    $monthCnNames = [
        '一月', '二月', '三月', '四月', '五月', '六月',
        '七月', '八月', '九月', '十月', '十一月', '十二月'
    ];
    $monthList = [];
    for ($month = 1; $month <= 12; $month++) {
        $monthList[] = [
            // 月份中文名称
            'name' => $monthCnNames[$month - 1],
            // 关联的年份
            'link_year' => $targetYear,
            // 月份数字
            'month_num' => $month,
            // 当前月份的天数,自动适配闰年2月的天数
            'days' => cal_days_in_month(CAL_GREGORIAN, $month, $targetYear)
        ];
    }
    return $monthList;
}

// 调用示例:获取2024年关联的月份列表
$months2024 = getLinkedMonthList(2024);

内容的提问来源于stack exchange,提问作者Nuwan Theekshana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:09:03