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
Share and Enjoy:
  • StumbleUpon
  • Digg
  • TwitThis
  • FriendFeed
  • del.icio.us
  • MySpace
  • Technorati
  • Facebook
  • Google Bookmarks
  • Live

Enjoy this article?

Consider subscribing to our RSS feed!

Share us Facebook, FriendFeed, Digg

Liked by

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

No Comments

No comments yet.

Sorry, the comment form is closed at this time.

Oyun