PHP项目中自动按奇偶数量拆分表单问题的实现求助
解决方案
首先我们需要先计算出左侧要展示的问题数量,不管总题数是奇数还是偶数,都可以用这个公式:$leftCount = (int)(($totalQuestions + 1) / 2);
比如总题数39时,(39+1)/2=20,刚好是左侧数量;总题数40时,(40+1)/2=20.5,取整后是20,左右各20题,完全符合需求。
接下来把问题列表拆分成左右两部分,然后循环渲染到表格里,就能适配问题数量动态增减的场景。下面是完整的代码示例:
<?php // 假设后端传来的问题列表存在$questions变量里 $totalQuestions = count($questions); $leftCount = (int)(($totalQuestions + 1) / 2); // 拆分左右问题列表 $leftQuestions = array_slice($questions, 0, $leftCount); $rightQuestions = array_slice($questions, $leftCount); ?> <table style="width: 100%; border-collapse: collapse;"> <?php foreach ($leftQuestions as $index => $leftQ): ?> <tr> <!-- 左侧问题列 --> <td style="border: 1px solid black; width: 50%; padding: 8px;"> <?= $index + 1 ?>. <?= $leftQ['question'] ?> </td> <!-- 右侧问题列,判断右侧是否有对应索引的问题 --> <td style="border: 1px solid black; width: 50%; padding: 8px;"> <?php if (isset($rightQuestions[$index])): ?> <?= $leftCount + $index + 1 ?>. <?= $rightQuestions[$index]['question'] ?> <?php endif; ?> </td> </tr> <?php endforeach; ?> </table>
代码解释
count($questions):自动获取总问题数量,不管题目增删都能实时计算array_slice:用来截取数组的一部分,把问题列表拆成左右两组- 循环遍历左侧问题时,同时检查右侧列表对应位置是否有问题,有就渲染,没有则留空,适配奇数题数的情况
- 问题编号:左侧从1开始递增,右侧从左侧数量+1开始递增,保证编号连续
如果要保留你原来的td colspan布局(一行三个td的结构),可以调整成下面的代码:
<?php $totalQuestions = count($questions); $leftCount = (int)(($totalQuestions + 1) / 2); $leftQuestions = array_slice($questions, 0, $leftCount); $rightQuestions = array_slice($questions, $leftCount); ?> <table style="width: 100%; border-collapse: collapse;"> <?php foreach ($leftQuestions as $index => $leftQ): ?> <tr> <!-- 左侧问题 --> <td colspan="4" style="border: 1px solid black; width: 60%; padding: 8px;"> <?= $index + 1 ?>. <?= $leftQ['question'] ?> </td> <!-- 右侧问题(如果存在) --> <td colspan="4" style="border: 1px solid black; width: 20%; padding: 8px;"> <?php if (isset($rightQuestions[$index])): ?> <?= $leftCount + $index + 1 ?>. <?= $rightQuestions[$index]['question'] ?> <?php endif; ?> </td> <td colspan="4" style="border: 1px solid black; width: 20%;"></td> </tr> <?php endforeach; ?> </table>
这样不管问题数量怎么变,都会自动计算左右拆分的数量,完全适配动态场景。
内容的提问来源于stack exchange,提问作者SuperXok2077
相关产品推荐
相关产品推荐

