Listing Items by Category in PHP

你。 提交于 2019-12-03 21:56:09

Add an ORDER BY category.category_name clause to your query so that as you loop through the resulting rows, the items in each category will be grouped together. Then, each time the category is different from the previous one seen, print out the category as the heading before printing the title.

$category = null;
foreach ($rows as $row) {
    if ($row['category_name'] != $category) {
        $category = $row['category_name'];
        print "<h1>".$category."</h1>\n";
    }
    print $row['book_title']."<br/>\n";
}

Order the results by category and then just iterate thru, putting a category header whenever the category name changes.

The ordering is most easily done in the SQL query. You don't even need an intermediate array.

SELECT category.category_name, book.book_title
FROM category LEFT OUTER JOIN book
               ON category.category_id = book.fk_category_id
ORDER BY category.category_name

And then for the PHP

$res = mysql_query($query);
$lastCategory = '';
while ($row = mysql_fetch_assoc($res))
{
    if($row['category_name'] != $lastCategory)
    {
       $lastCategory = $row['category_name'];
       echo "<br /><strong>$lastCategory</strong>";
    }        
    echo $row['book_title'] . ' <br />';
}

You do not need to put all your results into an array first. You can just fetch them as you go.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!