如何在PHP中通过循环按bs_column规则动态生成HTML表格
PHP动态生成符合bs_column规则的HTML表格实现方案
原代码核心问题
- 切换不同
bs_column类型字段时,未主动关闭之前未闭合的<tr>标签,导致HTML结构错乱 - 行计数的判断边界错误,无法正确在填满列后闭合行
- 循环结束后没有兜底逻辑关闭剩余未关闭的
<tr>标签 bs_column=4对应的<td>未设置宽度,会导致列宽不符合三等分预期
修复后完整代码
<?php $max_six_per_row = 2; $max_four_per_row = 3; $item_count_two = 0; $item_count_three = 0; $fields_html = ''; // 表格基础属性可根据需求调整,border属性仅方便调试查看效果 $fields_html .= '<table border="1" cellpadding="8" cellspacing="0"><tbody>'; // 公共闭包:关闭未结束的行,重置计数 $close_opened_row = function() use (&$fields_html, &$item_count_two, &$item_count_three) { if ($item_count_two > 0) { $fields_html .= "</tr>"; $item_count_two = 0; } if ($item_count_three > 0) { $fields_html .= "</tr>"; $item_count_three = 0; } }; foreach ($fields as $field) { // 转义特殊字符避免HTML注入、结构错乱 $field_name = htmlspecialchars($field['name']); if ($field['bs_column'] == 12) { // 先关闭之前未结束的6/4列行 $close_opened_row(); $fields_html .="<tr><td width='100%'>".$field_name."</td></tr>"; } elseif ($field['bs_column'] == 6) { // 先关闭4列的未结束行,避免不同列类型混排 if ($item_count_three > 0) { $close_opened_row(); } if ($item_count_two == 0) { $fields_html .="<tr>"; } $fields_html .="<td width='50%'>".$field_name."</td>"; $item_count_two++; // 填满2个就关闭行 if ($item_count_two == $max_six_per_row) { $fields_html .="</tr>"; $item_count_two = 0; } } elseif ($field['bs_column'] == 4) { // 先关闭6列的未结束行,避免不同列类型混排 if ($item_count_two > 0) { $close_opened_row(); } if ($item_count_three == 0) { $fields_html .="<tr>"; } $fields_html .="<td width='33.33%'>".$field_name."</td>"; $item_count_three++; // 填满3个就关闭行 if ($item_count_three == $max_four_per_row) { $fields_html .="</tr>"; $item_count_three = 0; } } } // 循环结束兜底关闭剩余未关闭的行 $close_opened_row(); $fields_html .= '</tbody></table>'; echo $fields_html; ?>
实现效果说明
完全匹配需求规则:
bs_column=12的字段永远单独占一行,不会和其他列类型混排bs_column=6的字段每2个占一行,剩余不足2个的单独占一行bs_column=4的字段每3个占一行,剩余1个或2个的都单独占一行- 自动转义字段名特殊字符,避免HTML结构被破坏
内容的提问来源于stack exchange,提问作者onlinegsali
相关产品推荐
相关产品推荐

