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

如何使用PHP将MySQL提取的学期课程数据渲染为指定格式的HTML表格

PHP转换MySQL学期课程数据为横向表格解决方案

问题原因

原有代码的核心问题是没有提前对数据按学期分组,直接遍历原始一维数据时无法对应到正确的列位置,且每次输出课程就单独创建行标签,导致所有内容堆叠在第一列。

实现步骤

  1. 先对原始三个数组做预处理,将课程按学期分组,同时收集所有出现的学期并排序
  2. 统计所有学期的最大课程数量,预留足够的表格行数(示例要求至少显示5行)
  3. 先渲染表头,输出所有学期编号
  4. 逐行渲染课程内容,每行对应不同学期的同序号课程,无对应课程则输出空单元格

完整代码实现

<?php
// 数据预处理:按学期分组,收集所有学期
$termCourses = [];
$allTerms = [];
$size = count($semester);

for ($i = 0; $i < $size; $i++) {
    $currentTerm = $semester[$i];
    // 初始化学期分组
    if (!isset($termCourses[$currentTerm])) {
        $termCourses[$currentTerm] = [];
        $allTerms[] = $currentTerm;
    }
    // 拼接课程与评估结果,空ASSESSED不显示括号
    $courseItem = $courses[$i];
    if (!empty($level[$i])) {
        $courseItem .= " ({$level[$i]})";
    }
    $termCourses[$currentTerm][] = $courseItem;
}

// 学期按数字升序排序
sort($allTerms);
// 统计最大课程数,至少显示5行和示例对齐
$maxCourseNum = max(array_map('count', $termCourses));
$totalRows = max($maxCourseNum, 5);
?>

<!-- 渲染目标HTML表格 -->
<div class="s-table-container">
<table class="s-table">
    <thead>
        <tr>
            <th>Term</th>
            <?php foreach ($allTerms as $term): ?>
                <th><?= $term ?></th>
            <?php endforeach; ?>
        </tr>
    </thead>
    <tbody>
        <?php for ($rowIndex = 0; $rowIndex < $totalRows; $rowIndex++): ?>
        <tr>
            <!-- 首列仅第一行显示Course -->
            <td><?= $rowIndex == 0 ? 'Course' : '' ?></td>
            <?php foreach ($allTerms as $term): ?>
                <td><?= isset($termCourses[$term][$rowIndex]) ? $termCourses[$term][$rowIndex] : '' ?></td>
            <?php endforeach; ?>
        </tr>
        <?php endfor; ?>
    </tbody>
</table>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:06:10