且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用PHP循环在单独的表中显示分组数据?

更新时间:2023-01-16 10:12:20

您将需要根据sid值对结果集数据进行分组".进行迭代时,请检查是否要更改组.

You will need to "group" your result set data based on the sid value. As you iterate, check if you are changing groups or not.

我也添加了一些改进.

  • 命名SELECT子句中的列,以便仅精确检索所需的内容.
  • 获取关联数组,而不是索引元素和关联元素的组合.
  • 分配一个临时变量以帮助您确定是继续sid组还是开始新的组(或者如果是第一次迭代,则不要写</table>.
  • implode()有助于消除很多代码膨胀.
  • Name the columns in your SELECT clause so that you only retrieve exactly what you need.
  • Fetch an associative array, not a combination of indexed and associative elements.
  • Assign a temporary variable to help you determine if you are continuing a sid group or starting a new one (or if it is the first iteration, don't write </table>.
  • implode() helps to remove a lot of the code bloat.

代码:

$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
}