php - Grouping Results from database -
i trying display results in category's based on id information data base creates category header on again.
for example:
title category demo cat 1
topic 1 cat 1title category demo cat 1
topic 2 cat 1title category demo cat 2
topic 3 cat 2
when should display:
title category demo cat 1
topic 1 cat 1topic 2 cat 1
title category demo cat 2
topic 3 cat 2
<table class="table table-bordered table-hover"> <?php $sql = "select * forums, forum_categories forum_categories.cat_id = forums.cat_id order 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>
you printing header each result mysql returns, each row. you're not distinguishing whenever "new" category found. can done simple creating temporary variable array. example:
$displayedcategories = array(); while (($row = mysqli_fetch_assoc($result)) != false) { if (!in_array($row['cat_id'], $displayedcategories)) { // new category, display , save in $displayedcategories $displayedcategories[] = $row['cat_id']; echo "<thead>"; echo "<tr>"; echo "<th colspan='4'>$cat_title</th>"; echo "</tr>"; echo "</thead>"; } // other stuff here... }
this way, "new" category that's not encountered, header printed once , category id saved $displayedcategories
array. if same category encountered again, header not output again.
Comments
Post a Comment