我如何使用 php 将 mysql 数据库中的数据分组到 html table 中

How can i group data from mysql database into an html table using php

我有两个 table 连接在一起,如下所示

    <?php 
    $userqry="
    SELECT * 
      FROM permission_category c
      JOIN permission_group g
        ON c.perm_group_id = g.id 
    ";
    $stmt = $conn2->prepare($userqry);
    $stmt->execute();
    while($row= $stmt->fetch()){
     } ?>
   <tr>
   <td><?php echo $row['name'];?></td>
   <td><?php echo $row['perm_group_name'];?>
   </td>
   <td>
   </tr>
<?php } ?>

结果如下

但是我要找的结果应该显示如下

我怎样才能做到这一点?

此代码“记住”循环中以前的名称。如果名称未更改,则不会显示:

<?php 
$userqry = "SELECT * FROM `permission_category` 
            INNER JOIN `permission_group` ON 
            `permission_category`.`perm_group_id`=`permission_group`.`id`";
$stmt = $conn2->prepare($userqry);
$stmt->execute();

$current_name="";
while ($row= $stmt->fetch()) {
  if ($row['name'] != $current_name) {
    $name = $row['name'];
    $current_name = $name;
  } else {
    $name = "";
  }
?>
<tr>
  <td><?php echo $name;?></td>
  <td><?php echo $row['perm_group_name'];?>
  </td>
  <td>
</tr>
<?php } ?>

注意:您应该在查询中添加 ORDER BY 以便以正确的方式对结果进行排序(可能已经排序)