multi level category listings / tree php function
I'm looking for a php function or mysql stored proc开发者_Go百科edure which outputs the following:
1: category 1 > category 2 > category 3 > category 4
2: category 1 > category 2 > category 3 > category 4
...
n: category n > category o > category p > category p
so basically i want last level category id and text which display all parent categories in hierarchy as above. I have the following table: categories(id,title,level,parentid); level increases with category depth.
I tried much on google but could not find a solution. can you please help me?
thanks -Navi
You can do somethig like this:
$result = mysql_query("SELECT * FROM categories WHERE level = 1");
$branches = 0;
$tree= array();
while($rows = mysql_fetch_array($result)){
echo "X->".$rows['title']."<br>";
$GLOBALS['tree'][$branches][] = $rows['title'];
getChildren($rows['id'], $branches);
$branches ++;
}
function getChildren($id, $index){
$query = "SELECT * FROM categories WHERE parentid = $id;";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result)){
echo $index."->".$rows['title']."<br>";
$GLOBALS['tree'][$index][] = $rows['title'];
getChildren($rows['id'], $index);
}
}
echo "<pre>";
print_r($tree);
echo "</pre>";
You will have all "branches" in the variable $tree, from then just use foreach to get through the branches...
Hope this helps
精彩评论