如何在表格中横向展示数据?解决表头重叠与重复条目问题
表格横向数据展示问题修复
问题现象
错误渲染效果:
Column A Column B Column C Column D Column E No Column No Column No Column No Column #1 20 30 40 50 30 25 15 10 #2 20 30 40 . 50. 30 25 15 10
期望的正确渲染效果:
Column A Column B Column C Column D Column E #1 20 30 40 50 #2 30 25 15 . 10
问题根源
原代码存在两个核心问题:
- 内层循环遍历所有候选人的分数,而非当前候选人对应的分数,导致每行重复输出全部分数,产生多余列
- 错误添加了空的
<tr></tr>标签,可能引发额外渲染异常
原代码:
<div class="table-responsive"> <table class="table table-striped table-bordered" style="width:100%"> <tbody class="text-center"> <?php foreach($candidatesf as $candidate): ?> <tr> <td><?php echo $candidate['fullname'] ?></td> <?php foreach($candscores as $candscore): ?> <?php echo "\t<td>"; ?><?php echo $candscore['score']; ?></td> <?php endforeach; ?> <tr></tr> <?php endforeach; ?> </tbody> </table> </div>
修复方案
需要确保每个候选人只输出自己对应的分数,同时移除无效的空行标签。以下是两种常见修复方式:
方式1:候选人数据自带分数列表
如果$candidate本身包含对应的分数数组(比如$candidate['scores']):
<div class="table-responsive"> <table class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> <th>Column D</th> <th>Column E</th> </tr> </thead> <tbody class="text-center"> <?php foreach($candidatesf as $candidate): ?> <tr> <td><?php echo $candidate['fullname'] ?></td> <?php foreach($candidate['scores'] as $score): ?> <td><?php echo $score; ?></td> <?php endforeach; ?> </tr> <?php endforeach; ?> </tbody> </table> </div>
方式2:通过关联键匹配分数
如果$candscores是按候选人ID关联的数组(比如键为候选人ID):
<div class="table-responsive"> <table class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> <th>Column D</th> <th>Column E</th> </tr> </thead> <tbody class="text-center"> <?php foreach($candidatesf as $candidate): ?> <tr> <td><?php echo $candidate['fullname'] ?></td> <?php foreach($candscores[$candidate['id']] as $score): ?> <td><?php echo $score; ?></td> <?php endforeach; ?> </tr> <?php endforeach; ?> </tbody> </table> </div>
关键修改点
- 新增
<thead>标签补充表头,解决表头缺失/重叠问题 - 内层循环改为遍历当前候选人的对应分数,而非所有分数
- 移除无效的
<tr></tr>空行标签 - 确保每行
<tr>标签正确闭合
内容的提问来源于stack exchange,提问作者Anon Syn
相关产品推荐
相关产品推荐

