Psy*_*che 1 php recursion hierarchical-data
我想编写一个递归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
Run Code Online (Sandbox Code Playgroud)
贝娄是表中数据的一个例子:
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
Run Code Online (Sandbox Code Playgroud)
谢谢.
fab*_*rik 14
function get_categories($parent = 0)
{
$html = '<ul>';
$query = mysql_query("SELECT * FROM `categories` WHERE `category_parent` = '$parent'");
while($row = mysql_fetch_assoc($query))
{
$current_id = $row['category_id'];
$html .= '<li>' . $row['category_name'];
$has_sub = NULL;
$has_sub = mysql_num_rows(mysql_query("SELECT COUNT(`category_parent`) FROM `categories` WHERE `category_parent` = '$current_id'"));
if($has_sub)
{
$html .= get_categories($current_id);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
print get_categories();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8355 次 |
最近记录: |