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

如何在表格中横向展示数据?解决表头重叠与重复条目问题

表格横向数据展示问题修复

问题现象

错误渲染效果:

Column AColumn BColumn CColumn DColumn ENo ColumnNo ColumnNo ColumnNo Column
#12030405030251510
#2203040. 50.30251510

期望的正确渲染效果:

Column AColumn BColumn CColumn DColumn E
#120304050
#2302515. 10

问题根源

原代码存在两个核心问题:

  1. 内层循环遍历所有候选人的分数,而非当前候选人对应的分数,导致每行重复输出全部分数,产生多余列
  2. 错误添加了空的<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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:10:14