我有以下功能,只有当至少有1个产品与该类别相关联时,才会返回带有产品类别的ul菜单。功能如下:
function getProductCategorieshome() {
$query = 'select id,
category,
title
from products_categories
where visible="1" and
parent="0"
group by category
order by category ASC';
$result = mysql_query($query) or
die('Mysql Error:'.mysql_error().'<br /> Query:'.$query);
$num_rows = mysql_num_rows($result);
if($num_rows){
echo '<ul id="menu" style="list-style:none;">';
$htm = '';
for($i=0; $i<$num_rows; $i++) {
$row = mysql_fetch_row($result);
//sub category
$query = 'select pc.id,
category,
pc.title,
p.id,
p.new
from products_categories pc,
products_to_categories ptc,
products p
where visible="1" and
parent="'.$row[0].'" and
pc.id=ptc.category_id and
p.id=ptc.product_id and
p.new="1" and
( expire_date>now() or expire_date=0)
group by category
order by category ASC';
$result1 = mysql_query($query) or
die('Mysql Error:'.mysql_error().'<br /> Query:'.$query);
$num_rows1 = mysql_num_rows($result1);
$q = 'select pc.id,
category,
pc.title,
p.id,
p.new
from products_categories pc,
products_to_categories ptc,
products p
where pc.id="'.$row[0].'" and
pc.id=ptc.category_id and
p.id=ptc.product_id and
p.new="1" and
( expire_date>now() or expire_date=0)
group by category
order by category ASC';
$r = mysql_query($q) or
die('Mysql Error:'.mysql_error().'<br /> Query:'.$q);
$num_rows2 = mysql_num_rows($r);
if($num_rows1>0) {
$sub_htm='';
for($j=0; $j<$num_rows1; $j++){
$row1 = mysql_fetch_row($result1);
$sub_htm .= '<li style="list-style:none;text-align:left;">
<a href="./shop/index.php?offers='.$row1[0].'" title="'.$row1[2].'">'.$row1[1].'</a></li>';
}
if(!empty($sub_htm)) {
$htm .= '<li style="list-style:none;text-align:left;">
<a href="./shop/index.php?offers='.$row[0].'" title="'.$row[2].'">'.$row[1].'</a><ul>'.$sub_htm.'</ul></li>';
}
} else {
for($s=0; $s<$num_rows2; $s++){
$rr = mysql_fetch_row($r);
$htm .= '<li style="margin:0px;padding:0px;text-align:left;">
<a href = "./shop/index.php?offers='.$rr[0].'" title="'.$rr[2].'">'.$rr[1].'</a></li>';
}
}
}
echo $htm;
echo '</ul>';
}
}
如果它们具有2级深度,则此函数返回正确的类别 - 因此我们有父类别和1级子类别,但是现在我需要具有无限的类别深度并且该函数需要再循环一次或者??? 请帮我解决这个问题。我知道mysql已弃用了:)
答案 0 :(得分:0)
最简单的解决方案是从products_categories中选择DISTINCT类别:
SELECT DISTINCT category FROM products_categories WHERE visible = 1
然后创建一个db过程,用于构建从每个叶节点到根节点的树路径
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `treePath`(in category_id int)
BEGIN
DECLARE parent int;
DECLARE current int;
SET @parent := NULL;
SET @current := category_id;
CREATE TEMPORARY TABLE tree_path_tmp(id int);
-- TRUNCATE tree_path_tmp;
WHILE @current DO
INSERT INTO tree_path_tmp SELECT @parent := parent_id FROM categories WHERE id = @current;
SET @current := @parent;
END WHILE;
SELECT * FROM tree_path_tmp;
END$$
DELIMITER ;
从现在开始,一旦将proc存储在RDBMS中,您就可以通过使用
调用该过程来获取路径CALL treePath($categoryThatHasVisibleProducts_id);
从那里......祝你好运! :)现在可以构建所有非隐藏类别的数组。
顺便说一下,看看嵌套集模型。
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/