Jump to content

Need some more help with recursive function


dhimo

Recommended Posts

Hello there. I have this recursive function which lists all categories and subcategories from the database. I have three fields.category_id, category_name and parent_id. Top category holds parent_Id = 0 while subcategories get the id from their parent. Here s the functions. Justsomeguy helped me with this and he probably will again :)

<?phpfunction listCategory($parent = 0, $level = 0){   // where parent of 0 means it's top-level   $retval = "";   $indent = "<br />";   for ($i=0; $i<$level; $i++) $indent .= "     ";		   $result = mysql_query("SELECT * FROM categories WHERE parent_id='$parent'");   while ($row = mysql_fetch_assoc($result))  {		extract($row);		$retval .= $indent . "<a href=\"?c=$category_id\">" . $category_name . "</a>";		$retval .= listCategory($category_id, intval($level) + 1);   }   return $retval;}?>

As the function is it lists all categories and subcategories. I want to list only top categories which have parent_id = 0 and I want to get appropriate children after getting the querystring as u can see above in the code.I want to mention to justsomeguy that his help is very appriciated and the reason i am posting a new thread is that is faster to get a response then paging to the prieviews threads which are far behind

Link to comment
Share on other sites

Simply remove the call to itself to only get the direct children to $parent. You don't need $level this way. You'll then have this:

<?phpfunction listCategory($parent = 0){   // where parent of 0 means it's top-level   $retval = "";   $indent = "<br />";   for ($i=0; $i<$level; $i++) $indent .= "     ";		   $result = mysql_query("SELECT * FROM categories WHERE parent_id='$parent'");   while ($row = mysql_fetch_assoc($result))  {		extract($row);		$retval .= $indent . "<a href=\"?c=$category_id\">" . $category_name . "</a>";   }   return $retval;}?>

Then, to get the children of the id in the query string, just call the function with it as a parameter, i.e:

<?	listCategory($_GET['c']);?>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...