PHP使用foreach生成HTML表格 按动态列头匹配填充对应单元格数据
实现方案
第一步:预处理比赛数据,按轮次分组
先把所有比赛数据按round字段分组,方便后续直接通过列头的轮次值快速获取对应比赛,避免每次都遍历全量匹配数据:
// 按round分组存储比赛,同一个轮次的所有比赛都存在对应下标下 $matchesByRound = []; foreach ($matches as $match) { $round = $match['match']['round']; $matchesByRound[$round][] = $match; }
第二步:完整表格渲染代码
整合列头生成和动态单元格填充的逻辑,同时优化原代码中未生效的HTML转义、以及分数读取逻辑(避免分数为两位数时取值错误):
<?php if (count($round) > 0): // 取所有列头对应的轮次值,保持原顺序 $roundHeaders = array_values($round[0]); ?> <table> <thead> <tr> <?php foreach ($roundHeaders as $header): ?> <th><?php echo htmlentities($header) ?></th> <?php endforeach; ?> </tr> </thead> <tbody> <tr> <?php foreach ($roundHeaders as $currentRound): ?> <td> <?php // 存在对应轮次的比赛才输出内容 if (isset($matchesByRound[$currentRound])) { foreach ($matchesByRound[$currentRound] as $match) { // 用explode拆分比分更稳妥,支持两位数及以上的分数 $scores = explode('-', $match['match']['scores_csv']); $score1 = $scores[0] ?? 0; $score2 = $scores[1] ?? 0; $id1 = $match['match']['player1_id']; $id2 = $match['match']['player2_id']; echo "Table: ".$match['match']['player1_votes']."<br>"; echo htmlentities($participants[$id1]["name"].$participants[$id1]['misc']).": ".$score1."<br>"; echo htmlentities($participants[$id2]["name"].$participants[$id2]['misc']).": ".$score2."<br>"; } } ?> </td> <?php endforeach; ?> </tr> </tbody> </table> <?php endif; ?>
说明
- 原代码中
array_map('htmlentities', $colhead)没有接收返回值,转义不生效,新代码中单独对每个输出内容做转义,避免XSS风险 - 改用
explode拆分比分,兼容大于9的分数场景 - 直接复用原
$round的列头顺序,保证列头和单元格内容一一对应
内容的提问来源于stack exchange,提问作者Jennifer Hamilton
相关产品推荐
相关产品推荐

