如何使用 PHP 和 HTML 在表的每一行中显示两条记录


How to display two records in each rows of a table using PHP and HTML?

在我的网站上,我想在页面中显示学生的详细信息。我正在使用表格进行设计。我需要的是,我想在每行展示两个学生。因此,如果数据库中总共有 10 名学生,则显示页面中应该有 5 行,每行有两个学生。

我怎样才能做到这一点?

$students = Array('S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'S10');
$html = '<table>';
for ($i = 0; $i<count($students); $i+=2)
{
    $html.= '<tr>
                <td>'.$students[$i].'</td>
                <td>'.$students[$i+1].'</td>
            </tr>'; 
}
$html.= '</table>';

因此,假设您有一个包含 10 名学生的数组,例如$myStudents

要创建表,请尝试以下代码

<table>
<tr>
  <td>Student Name</td>
  <td>Student Name</td>
</tr>
<?php
 $cols = 2;
 $colNum=0;
 $trOpened = false;
 for($i=0;$i<count($myStudents);$i++):
    if( $colNum % 2 != 0 || $colNum==0 ){
       echo "<tr>";
        $trOpened = true;
    }
   ?>
     <td><?=$myStudents[$i]['StudentName']?></td>
 <?php
   $colNum++;
   if(  $trOpened == true && $colNum % 2 == 0 ){
        echo "</tr>";
        $trOpened = false;
        $colNum = 0;
   }
 endfor;

   ?>
</table>