Press enter to see results or esc to cancel.

Recursive Category Listing

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
  • Drinks
    • Soft
      • Fruit Juice
        • Apple Juice
        • Strawberry Juice
      • Milk
Comments

Comments are disabled for this post