PHP递归函数检索类别的所有子项
我想编写一个递归 PHP 函数来检索指定类别的所有子项。我尝试了此处描述的方法,但没有输出我所期望的。
我的类别表如下所示:
CREATE TABLE `categories` (
`category_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`category_name` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`category_slug` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`category_parent` smallint(5) unsigned NOT NULL DEFAULT '0',
`category_description_ro` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`category_description_en` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1
下面是表中数据的示例:
category id | category name | category_parent
1 Categoria 1 0
2 Categoria 2 0
3 Categoria 3 0
4 Categoria 1.1 1
5 Categoria 1.2 1
6 Categoria 1.3 1
7 Categoria 1.1.2 4
谢谢。
I would like to write a recursive PHP function to retrive all the children for the specified category. I tried the one described here but it didn't output what I have expected.
My categories table looks like this:
CREATE TABLE `categories` (
`category_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`category_name` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`category_slug` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`category_parent` smallint(5) unsigned NOT NULL DEFAULT '0',
`category_description_ro` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`category_description_en` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1
Bellow is an example of data in the table:
category id | category name | category_parent
1 Categoria 1 0
2 Categoria 2 0
3 Categoria 3 0
4 Categoria 1.1 1
5 Categoria 1.2 1
6 Categoria 1.3 1
7 Categoria 1.1.2 4
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现了一个非常简单的示例,它适用于从数据库检索的一组类别。查询“SELECT * FROMcategories”将创建所有类别的数组。
在我的类别表中,有字段“id”、“parent_id”和“name”。就这样。
基本类别的父 ID 设置为 0。子类别的 Parent_id 设置为父类别 ID。简单吧?代码如下:
$categories 数组是一个 sql 查询“SELECT * FROMcategories”的效果
I've found quite a simple example that works over an array of categories retrieved from a DB. The query "SELECT * FROM categories" will create an array of all the categories.
In my categories table I have the fields 'id','parent_id'and 'name'. That's all.
Base categories have parent id set as 0. Subcats have parent_id set as parent category ID. Simple right ? Here is the code :
$categories array is an effect of one sql query "SELECT * FROM categories"
这是我用来显示嵌套链接的东西,它只进行一个数据库查询,然后将结果缓存在一个有用的数组中。
Here is something I use for displaying nested links, it only makes one DB query then caches the results in a useful array..