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

如何使用PHP获取多维数组中1月、2月的缺失日期?

PHP获取指定月份缺失日期实现方案

首先明确两种常见需求场景,你可以根据自己的需要选择:

场景1:获取当月全部日期中缺失的部分

即1月取1-31日的全量日期对比,2月取1-28/29日全量对比:

实现代码

// 示例数组
$a = array (
  array("jan",1,2,3,5),
  array("feb",1,2,4,5),
);

// 预设月份和数字映射,用于动态计算天数
$monthMap = ['jan' => 1, 'feb' => 2];
// 可自定义年份,会自动适配2月闰年天数
$targetYear = 2024;

$missingDates = [];
foreach ($a as $item) {
    $monthKey = array_shift($item);
    $existDays = $item;
    // 动态获取当月总天数
    $totalDays = cal_days_in_month(CAL_GREGORIAN, $monthMap[$monthKey], $targetYear);
    // 生成当月全量日期数组
    $fullDays = range(1, $totalDays);
    // 计算缺失日期,重置索引后存入结果
    $missingDates[$monthKey] = array_values(array_diff($fullDays, $existDays));
}

// 打印结果
print_r($missingDates);

场景2:仅获取现有日期最大值之前的缺失部分

即示例1月现有最大日期为5,仅返回4;2月现有最大日期为5,仅返回3,只需要把生成全量日期的代码行替换为:

$fullDays = range(1, max($existDays));

输出示例(场景2)

Array
(
    [jan] => Array
        (
            [0] => 4
        )
    [feb] => Array
        (
            [0] => 3
        )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:15:09