php - 如何使用 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
.
这是我要存档的样本
解决方案
您将需要根据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
}
推荐阅读
- c - 如何将关系运算符与随机数生成器一起使用 (c)
- python - 有没有办法将 OneHot 编码的 SciPy 稀疏矩阵应用于 PCA?
- javascript - Javascript 中的柯里化函数:在 for 循环中使用参数作为属性
- python - 从 Firebase 中的字典中提取单个数据(使用 Pyrebase 和 Flask)
- angular - “ShoppingCartComponent”类型上不存在属性“myForm”
- python - 如何将数据帧中的字节值转换为python中的常规整数
- r - 重命名 JSON 实体流
- r - 找到所有具有共同索引的数字 - R
- regex - htaccess 从 url 中删除段并重定向到 https 和 www
- python - 取熊猫中每一列的行均值(python)