【问题标题】:Insert tr after every third loop每三个循环后插入 tr
【发布时间】:2012-02-18 23:31:10
【问题描述】:

我正在用 PHP 做一个论坛。我必须在表格中显示所有论坛类别,为此,我使用了一个 while 循环。但是,我希望每个表行中只有 3 个 td。为了遍历类别,我在查询中使用了一个 while 循环,所以我认为我不能在这里使用模数。

【问题讨论】:

  • 您可以使用模运算符%,只需在循环之前创建一个增量变量$i=0,并在while 循环的每次迭代中递增它++$i

标签: php html-table modulus


【解决方案1】:

为什么不能使用模数?只需在某处添加一个计数器,如果它命中 % 3 == 0 则重置计数器并执行您的操作。

您可能需要为 first 和 last 做一些额外的 if's 和类似的事情,但没有理由不使用一段时间的模数。

$i=0;
while(guard()){
    if($i % 3 == 0){
       //ploing
    }
 $i++
}

【讨论】:

  • 啊,太棒了!我必须掌握这个模数的窍门。
【解决方案2】:

此代码将关闭所有多余的行:

<table>
<?php
$columns = 3;
$i = 0;
while($row = mysql_fetch_array($result)){
    $i++;
    //if this is first value in row, create new row
    if ($i % $columns == 1) {
        echo "<tr>";
    }
    echo "<td>".$row[0]."</td>";
    //if this is last value in row, end row
    if ($i % $columns == 0) {
        echo "</tr>";
    }
}
//if the counter is not divisible by the number of columns, we have an open row
$spacercells = $columns - ($i % $columns);
if ($spacercells < $columns) {
    for ($j=1; $j<=$spacercells; $j++) {
        echo "<td></td>";
    }
    echo "</tr>";
}
?>
</table>

【讨论】:

  • 谢谢你!这个社区绝对是我遇到的最有帮助的社区!
【解决方案3】:

我还没有测试过代码,但逻辑应该可以工作:

<Table>
<?php
$i = 0;
while($row = mysql_fetch_array($result)){
    if($i == 0){
        echo"<TR>";
    }
    echo"<td>".$row[0]."<TD>";
    $i++;
    if($i == 3)
    {
        $i = 0;
        echo"</tr>"
    }
}
if($i ==1){
    echo "<td></td><td></td></tr>";
}
if($i ==2)
{
    echo "<td></td></tr>";
}
?>
<table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多