我能否修改我的列,以便在需要时根据行中的项目数添加 colspan
?
场景:
假设我有 5 个项目,我需要一行/4 列,下一行 1 列 colspan="4"
假设我有 6 个项目,我需要 1 行/4 列,下一行,2 列 colspan="2"
假设我有 7 个项目,我需要 1 行/4 列,下一行,2 列没有 colspan,+ 1 列有 colspan="2"
这是我现有的代码:
echo '<table width="100%" cellpadding="10" cellspacing="5">' . PHP_EOL;
$colSpan = 4;
$rows = 0;
for($i = 0; $i < $tmpCt; $i++) {
// At column 0 you create a new row <tr>
if($i % $colSpan == 0) {
$rows++;
echo "<tr>\n";
}
// if only 1 item in the row, need to add colspan="4", 2 items colspan="2" for 2 <td>'s, 3 items 1 @ colspan="2" + 2 <td>'s
echo '<td width="25%" align="center" valign="middle">' . $tmpRet[$i]['sponName'] . '</td>' . PHP_EOL;
// At column 3 you end the row </tr>
echo $i % $colSpan == 3 ? "</tr>\n" : "";
}
// Say you have 5 columns, you need to create 3 empty <td> to validate your table!
for($j = $i; $j < ($colSpan * $rows); $j++) {
echo "<td> </td>\n";
}
// Add the final <tr>
if(($colSpan * $rows) > $i) {
echo "</tr>\n";
}
echo '</table>';
最佳答案
好吧,算术有用的时候!
您需要的是在每个级别使用模运算。
这是我的解决方案:
$tmpRet = array(
array(1),
array(1, 2, 3),
array(1, 2, 3, 4, 5, 6, 7),
array(1, 2, 3, 4, 5),
array(1, 2),
array(1, 2, 3, 4, 5, 6),
array(),
array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
);
$lencol = count($tmpRet);
echo '<table border="1" width="800px" cellpadding="10" cellspacing="5">'.PHP_EOL;
$colspan = 4;
for($i = 0; $i < $lencol; $i++) {
$bg = 'style="background-color: #'.rand(100, 999).'"';
$row = $tmpRet[$i];
$lc = count($row);
$offset = 0;
if ($lc>$colspan) {
$ct = floor($lc/$colspan);
$offset = $ct * $colspan;
$m = 0;
for ($k = 0; $k<$ct; $k++) {
echo '<tr '.$bg.' >';
for ($l = 0; $l<$colspan; $l++) {
echo '<td>'.$row[$m].'</td>';
$m++;
}
echo '<tr>';
}
}
$mod = $lc % $colspan;
switch ($mod) {
case 1:
echo '<tr '.$bg.' ><td colspan="4">'.$row[$offset].'</td></tr>';
break;
case 2:
echo '<tr '.$bg.' ><td colspan="2">'.$row[$offset].'</td><td colspan="2">'.$row[$offset+1].'</td></tr>';
break;
case 3:
echo '<tr '.$bg.' ><td>'.$row[$offset].'</td><td>'.$row[$offset+1].'</td><td colspan="2">'.$row[$offset+2].'</td></tr>';
break;
}
}
echo '</table>';
这就是它的样子:
希望对你有帮助
编辑:这仅适用于 $colspan=4
,如果您需要更动态的东西,请考虑用其他东西替换 switch 语句...也许是嵌套的循环...
关于php - 根据项目计数修改列跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320148/