在PHP中按类别列出项目 [英] Listing Items by Category in PHP

查看:64
本文介绍了在PHP中按类别列出项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我在PHP中按类别列出项目吗?

Can someone help me with listing items by category in PHP?

我正在尝试按类别创建一个简单的图书清单:

I'm trying to create a simple list of books by category:

JavaScript
JavaScript模式
面向对象的JavaScript

JavaScript
JavaScript Patterns
Object-Oriented JavaScript

Ajax
Ajax权威指南
防弹Ajax

Ajax
Ajax Definitive Guide
Bulletproof Ajax

jQuery
jQuery食谱
学习jQuery 1.3

jQuery
jQuery Cookbook
Learning jQuery 1.3

我在数据结构或SQL查询方面没有问题:

I have no problems with the data structure or SQL query:

BOOK:     book_id, book_title, fk_category_id  
CATEGORY: category_id, category_name

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

我的问题是我不知道如何编写PHP脚本来列出每个类别标题下的书籍.

My problem is that I don't know how to write the PHP script to list the books under each category header.

我了解足够多,可以将结果集放入一个数组中,但是然后我就迷住了使用该数组对项目进行分组的情况,如图所示.

I know enough to get the result set into an array, but then I'm stumped on using that array to group the items as shown.

另一个Stack问题几乎解决了同样的问题,但是响应没有解决PHP代码:列表类别的项目

Another Stack question addresses almost the same thing, but the responses stop short of solving the PHP code: List items by category

谢谢!

推荐答案

在查询中添加ORDER BY category.category_name子句,以便在循环搜索结果行时,每个类别中的项目将分组在一起.然后,每次类别与上一个类别都不相同时,请在打印标题之前将类别打印为标题.

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";
}

这篇关于在PHP中按类别列出项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆