簡體   English   中英

如何使用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_chunk()或設置為循環:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM