首页 > 解决方案 > 如何使用 PHP 循环在单独的表中显示分组数据?

问题描述

我是 phpmysqli 的新手。这是我所拥有的以及正在努力实现的目标:我将根据建议进行更新; 数据库样本数据

我想在一个页面上显示数据,并根据他们的 sid 为每个学生提供单独的表格。到目前为止,这是我尝试过的;

<?php
include_once 'dbcon.php';

$results = $MySQLiconn->query('SELECT * FROM activitybook');

$students = [];

foreach ( $results->fetch_array() as $activity ) {
    $students[$activity['sid']][] = $activity;
}

foreach($students as $sid=>$activities) {
    foreach($activities as $activity) {
         echo
                    "<table><tr>
                        <th>SID</th>
                        <th>Date</th>
                        <th>FName</th>
                        <th>LName</th>
                        <th>activity</th>
                        <th>time</th>
                        <th>score</th>
                        </tr>
                <tr>
                    <td>" . $sid . "</td>
                    <td>" . $activity['fname'] . "</td>
                    <td>" . $activity['lname'] . "</td>
                    <td>" . $activity['activity'] .  "</td>
                    <td>" . $activity['atime'] .  "</td>
                    <td>" . $activity['ascore'] .  "</td>
                </tr></table>";
    }
}
?>

这就是我得到的

我想要实现的是每个sid. 这是我要存档的样本

标签: phploopshtml-tablegroupingmysqli-fetch-array

解决方案


您将需要根据sid值对结果集数据进行“分组”。迭代时,检查您是否正在更改组。

我还添加了一些改进。

  • 命名 SELECT 子句中的列,以便您只检索您需要的内容。
  • 获取关联数组,而不是索引元素和关联元素的组合。
  • 分配一个临时变量来帮助您确定是继续一个sid组还是开始一个新的组(或者如果它是第一次迭代,不要写</table>.
  • implode()有助于消除大量的代码膨胀。

代码:

$res = $conn->query("SELECT sid, fname, lname, activity, atime, ascore FROM activitybook ORDER BY sid");
$tmp = null;
$colheads = ['SID', 'FName', 'LName', 'activity', 'time', 'score'];
while ($row = $res->fetch_assoc()) {   // don't produce more elements per row than needed
    if ($tmp != $row['sid']) {  // determine if a new group / sid value
        if ($tmp !== null) {
            echo '</table><br>';  // close the previous table
        }
        echo '<table border=1><tr><th>' , implode('</th><th>', $colheads) , '</th></tr>';  // start a new table & add headings
    }
    echo '<tr><td>' , implode('</td><td>', $row) , '</td></tr>';  // display the row data
    $tmp = $row['sid'];   // DUH, I FORGOT TO UPDATE $tmp!
}
if ($tmp !== null) {
    echo '</table>';  // close the final table -- so long as there was at least one row in the result set
}

推荐阅读