Recursive Category Listing
7
Jan0
Jan0
Webmasters allways use category trees, i wrote a function about creating category trees with using recursive function.
<?php
header('Content-Type: text/html; charset=UTF-8');
include($_SERVER['DOCUMENT_ROOT']."/mysql.inc.php");
function categories($firstCategory,$node)
{
$kQ = mysql_query("SELECT * FROM categories WHERE category= ".$firstCategory);
if(mysql_num_rows($kQ) > 0)
{
echo(str_repeat("\t",$node+1)."<ul>\n");
$node++;
while($k = mysql_fetch_array($kQ))
{
//str_repeat is for "view source" format, we set TAB character for readable HTML
echo(str_repeat("\t",$node)."<li>".($node+1)." ".$k["name"]."</li>\n");
// Recursive, call function it self
categories($k["id"], $node);
}
echo(str_repeat("\t",$node)."</ul>\n");
}
}
categories(0,-1);
?>
Output :
- Food
- Fruits
- Apple
- Banana
- Vegetables
- Tomatoes
- Aborgin
- Fruits
- Drinks
- Soft
- Fruit Juice
- Apple Juice
- Strawberry Juice
- Milk
- Fruit Juice
- Soft

