如何使用while或for每隔五个单元格更改一次表行


How to change table row on every fifth cell using while or for?

假设我们有一个查询,它给出了数据库记录的结果。我想把那些记录放在一张表上,但不喜欢一行接一行。我想制作一个表格,每隔五个单元格就会改变一行。如何使用whilefor执行此操作?

这只是我现在做的一个例子,但我不能让它每五个单元格就改变一行。。。

<table>
<tr>
<?php $count = 0; while ($count <= 5){ ?>
<td><?php echo $id[$count]->id; $usrname[$count]->usrname;</td>
<?php $count++;}?>
</tr>
</table>

知道吗???

使用模运算:

if($count % 5 == 4) {
  // end the current row, and start a new one
  echo "</tr><tr>";

它将$count除以5并取余数。因此,每5个步骤中就有一次是4(在$count中是4、9、14等),您可以为每五个记录生成不同的内容。


如果你把这个应用到你的代码示例中,你会得到:

<table>
<tr>
<?php
$count = 0;
while ($count <= 5) {
  if($count % 5 == 4) {
    // Generate a new row
    echo "<'tr><tr>";
  }
  ?><td><?php echo $id[$count]->id." ".$usrname[$count]->usrname;?></td><?php
  $count++;
}
?>
</tr>
</table>

在while或for之前使用array_cchunk()或设置为循环:

if($count % 5 == 0) {
   echo "</tr><tr>";
   $count = 0;
}

这样的东西可以工作。您也可以将其与内部for循环组合。但工作代码在很大程度上取决于您在其中循环的Array。因此,您可能需要自定义以下代码以适应您的设置。

请注意,我消除了While循环,因为您没有提供实际的数组。你基本上可以把它放在<tr>之前。

<table>
    // you may start your while loop here
    <tr>
        <td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
        <td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
        <td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
        <td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
        <td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
    </tr>
</table>