从数据库分组结果

时间:2016-04-19 18:36:32

标签: php

我正在尝试根据ID显示结果类别我从数据库中获取信息,但它会重新创建一个类别标题。

例如:

  

标题类别演示猫1   话题1猫1

     

标题类别演示猫1   话题2猫1

     

标题类别演示猫2   话题3猫2

何时显示:

  

标题类别演示猫1   话题1猫1

     

主题2 cat 1

     

标题类别演示猫2   话题3猫2

<table class="table table-bordered table-hover">
    <?php

$sql = "SELECT * FROM forums, forum_categories WHERE forum_categories.cat_id = forums.cat_id ORDER BY forum_categories.cat_id";
$result = query($sql);

while (($row = mysqli_fetch_assoc($result)) != false) {

    $cat_id = $row['cat_id'];    
    $cat_title = $row['cat_title'];

    echo "<thead>";
             echo "<tr>";
                 echo "<th colspan='4'>$cat_title</th>";
            "</tr>";
         echo "</thead>";
         echo "<tbody>";


    $forums_cat_id = $row['cat_id'];
    $forum_name = $row['forum_name']; 
    $forum_desc = $row['forum_desc'];
    $forum_last_post_id = $row['forum_last_post_id'];

    echo "<tr>";

    echo "<td>$forums_cat_id</td>";
    echo "<td>$forum_name<br>$forum_desc<br>Admin</td>";
    echo "<td>0</td>";
    echo "<td>0</td>";  
    echo "</tr>";
}

?>   
    </tbody>
</table>

2 个答案:

答案 0 :(得分:0)

<table class="table table-bordered table-hover"><tbody>
    <?php

    $sql = "SELECT * FROM forums, forum_categories WHERE forum_categories.cat_id = forums.cat_id ORDER BY forum_categories.cat_id";
    $result = query($sql);
    $cur_cat = '';
    while (($row = mysqli_fetch_assoc($result)) != false) {

        $cat_id = $row['cat_id'];    
        $cat_title = $row['cat_title'];

        if($cat_title != $cur_cat) {
            echo "<thead>";
                 echo "<tr>";
                     echo "<th colspan='4'>$cat_title</th>";
                "</tr>";
            echo "</thead>";
            $cur_cat = $cat_title;
         }


        $forums_cat_id = $row['cat_id'];
        $forum_name = $row['forum_name']; 
        $forum_desc = $row['forum_desc'];
        $forum_last_post_id = $row['forum_last_post_id'];

        echo "<tr>";

        echo "<td>$forums_cat_id</td>";
        echo "<td>$forum_name<br>$forum_desc<br>Admin</td>";
        echo "<td>0</td>";
        echo "<td>0</td>";  
        echo "</tr>";
    }

    ?>
</tbody></table>

答案 1 :(得分:0)

您正在为每行返回MySQL返回的每个结果的标题。因此,无论何时找到“新”类别,您都无法区分。通过创建像数组这样的临时变量,可以非常简单地完成此操作。例如:

$displayedCategories = array();

while (($row = mysqli_fetch_assoc($result)) != false) {
    if (!in_array($row['cat_id'], $displayedCategories)) {
        // This is a new category, display it and save it in $displayedCategories
        $displayedCategories[] = $row['cat_id'];
        echo "<thead>";
        echo "<tr>";
        echo "<th colspan='4'>$cat_title</th>";
        echo "</tr>";
        echo "</thead>";
    }

    // Do the other stuff here...
}

这样,任何未遇到的“新”类别,标题打印一次,类别ID保存到$displayedCategories数组。如果再次遇到相同的类别,则不会再次输出标题。