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

PHP实现将学生日程数组渲染为月度日历样式HTML表格问题

PHP 学生月度日程日历表格实现方案

修正的核心逻辑如下:

  • 补全学生数据存储结构,同步存储ID、姓名、日程日期,避免学生数据丢失
  • 修正表头逻辑:前两列为学生ID、学生姓名,后续列依次展示当月1日到当月最后一天
  • 修复DatePeriod默认不包含结束日期的问题,避免日程最后一天统计遗漏
  • 新增同学生多日程日期合并逻辑,避免同一学生重复生成表格行
  • 优化单元格渲染逻辑:有日程的日期单元格增加背景色标记,无日程的日期展示为空

完整实现代码:

// 初始化查询的年月,可根据实际需求修改
$year = 2024;
$month = 9;

// 获取当月总天数
$totalDays = cal_days_in_month(CAL_GREGORIAN, $month, $year);

// 渲染表格头部
echo "<table border='1' cellpadding='5' cellspacing='0'>";
echo "<tr>";
echo "<th>学生ID</th><th>学生姓名</th>";
for ($j = 1; $j <= $totalDays; $j++) {
    echo "<th>{$j}</th>";
}
echo "</tr>";

// 读取学生基础数据
$file = file_get_contents('MOCK_DATA-100.json');
$data = json_decode($file);

// 读取日程数据
$file2 = file_get_contents('calendar.json');
$data2 = json_decode($file2);

// 初始化学生日程数组,避免同一学生重复录入
$stuArr = [];
foreach($data as $student) {
    $stuArr[$student->id] = [
        'name' => $student->name,
        'dates' => []
    ];
}

// 匹配学生日程,合并日期
foreach($data2 as $cal) {
    $stuId = $cal->resource;
    // 跳过不存在的学生ID
    if(!isset($stuArr[$stuId])) continue;

    $start  = new DateTime(substr($cal->start, 0, 10));
    $end    = new DateTime(substr($cal->end, 0, 10));
    // 修正DatePeriod默认不包含结束日期的问题
    $end->modify('+1 day');
    $interval = DateInterval::createFromDateString('1 day');
    $period   = new DatePeriod($start, $interval, $end);
    
    foreach ($period as $dt) {
        // 只统计当前年月的日期
        if($month != $dt->format('n') || $year != $dt->format('Y')) {
            continue;
        }
        $day = $dt->format("j");
        // 日期去重,避免重复标记
        if(!in_array($day, $stuArr[$stuId]['dates'])) {
            $stuArr[$stuId]['dates'][] = $day;
        }
    }
}

// 渲染每个学生的日程行
foreach($stuArr as $id => $stuInfo) {
    $name = $stuInfo['name'];
    // 转成键值对提升匹配效率
    $hasDates = array_flip($stuInfo['dates']);
    echo "<tr>";
    echo "<td>{$id}</td><td>{$name}</td>";
    for ($d = 1; $d <= $totalDays; $d++) {
        if(isset($hasDates[$d])) {
            // 有日程的单元格添加背景色,可自行修改样式
            echo "<td style='background: #a5e9a5'>{$d}</td>";
        } else {
            echo "<td></td>";
        }
    }
    echo "</tr>";
}

echo "</table>";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:48:05