PHP开发学校管理系统时subjects表头与scores表数据索引不匹配求助
问题修复方案
核心问题有3个:
- 原代码输出分数时,每个分数单独包裹
<tr>标签,导致每个分数占单独一行,和表头的单行列结构不匹配 - 没有建立科目和分数的映射关系,存在缺考/无对应分数时会出现整体错位
- 原代码表格头标签书写错误,
<head>是网页头部标签,表格头部需用<thead>
修改后完整代码
<table class="table table-striped table-bordered"> <thead> <tr> <?php // 查询科目,同时保存科目ID和名称的映射数组用于后续匹配分数 $subjects = []; $view_subject = $config->prepare("SELECT * FROM subjects ORDER BY sub_id ASC"); $view_subject->execute(); while($row = $view_subject->fetch()){ $subId = $row['sub_id']; $subName = htmlspecialchars($row['sub_name']); $subjects[$subId] = $subName; ?> <th class="text-center" style="background-color:#395C7F;color:#fff;"><?php echo $subName;?></th> <?php } ?> </tr> </thead> <tbody> <?php // 查询分数,存为「科目ID => 分数值」的键值对数组,无需循环输出 $scoreMap = []; $view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC"); $view_scores->execute(['random_id' => $rand_ID]); while($row = $view_scores->fetch()){ $subId = $row['score_sub_id']; // 可根据需求替换为期末分score_final_amount $scoreMap[$subId] = htmlspecialchars($row['score_mid_amount']); } ?> <tr> <?php // 遍历科目数组输出分数,顺序和表头完全一致 foreach($subjects as $subId => $subName){ // 无对应分数的科目显示横杠占位 $score = isset($scoreMap[$subId]) ? $scoreMap[$subId] : '-'; ?> <td class="text-black" data-title="<?php echo $subName;?>"><?php echo $score;?></td> <?php } ?> </tr> </tbody> </table>
调整说明
- 科目查询增加
ORDER BY sub_id ASC保证表头顺序固定 - 通过
$scoreMap映射数组直接按科目ID匹配分数,无论是否有缺考科目都不会出现位置错位 - 所有分数放在同一个
<tr>标签内,和表头的列结构完全对应
内容的提问来源于stack exchange,提问作者Mohamed Saeed Ahmed
相关产品推荐
相关产品推荐

