Page 1 of 1
Recursing a tree menu
Posted: Thu Jul 13, 2006 2:04 am
by vivekjain
Hi,
I am developing an application in PHP and MySQL. I need to display Cagtegories, Sub-Categories, etc in a drop down and it needs to be this in this format in the drop down:
Category1
SubCategory1
SubSubCategory1
SubCategory1_1
SubSubCategory1_1
Category2
Can anyone please help me with this?
Thanks
Posted: Thu Jul 13, 2006 2:22 am
by vivekjain
These need to be indented:
Code: Select all
Category1
SubCategory1
SubSubCategory1
SubCategory1_1
SubSubCategory1_1
Category2
Posted: Thu Jul 13, 2006 4:46 am
by ok
Please give more information on your DB/table structure, on how you want the drop down menu to behave...
Posted: Thu Jul 13, 2006 4:57 am
by vivekjain
The table structure:
Code: Select all
category_id parent_id category_name
1 0 Category 1
2 1 SubCategory1
if its a Top Level Cateogry - the parent_id is 0
These needs to be populated in a drop down, with the indentation. Actually, a page lists links which are associated with a category, and if we need to change the category for a link, we can use the drop down to select another category/sub-cat and save.
I hope I am clear.
Thanks
Posted: Thu Jul 13, 2006 9:52 am
by pickle
I'd get all the categories & put them in a nested array - one that reflects the order you want & the heirarchy
ie:
Code: Select all
[category1][subcategory1[subsubcategory1]
[subcategory2][subsubcategory1_1]
etc.
Then, loop through that array recursively, with each call to the function adding an indentation (with CSS or  ).
Posted: Thu Jul 13, 2006 10:01 am
by onion2k
http://www.sitepoint.com/article/hierar ... a-database
Much nicer than using parent ids .. but a lot more complicated.
Posted: Thu Jul 13, 2006 10:02 am
by MrPotatoes
i just finished this in just this fashion last night:
its done in ADODB so if it doesn't make sense check the manual out but i did two queries cuz i couldn't figure out how to do it in one. doing two queries is equivalent to making two tables FYI
Code: Select all
function showMainAndSubCategories
{
$queryStatement = "SELECT * FROM " . $this->pref . "forums where forum_parent =0";
$result = $this->sql->execute($queryStatement);
// this is until it's the end of the table
while (!$result->EOF)
{
this is the name of the main category
echo $result->fields['forum_name'].' <BR> ';
$queryStatement = " SELECT * FROM " . $this->pref . "forums where forum_parent = " .$result->fields['forum_id'];
$result2 = $this->sql->execute($queryStatement);
while (!$result2->EOF)
{
echo $result2->fields['forum_name'] . " <br>";
// move next one
$result2->moveNext();
}
// move next one
$result->moveNext();
}
}
********* code parser
pickle | language please
Posted: Thu Jul 13, 2006 1:12 pm
by MrPotatoes
so....ahh....did you ever figure it out?
Posted: Fri Jul 14, 2006 1:26 am
by vivekjain
Hi onion2k,
I tried the link that you sent, and it works well. Thanks for your help. Appreciate it.
Thanks to everyone, who tried to help me on this.