Page 1 of 1

How to implement dynamic hierarchical menu structure?

Posted: Mon Apr 13, 2009 12:52 pm
by yogi
Hi All,

I need to implement dynamic menu structure using PHP and MySQL. My menu details are in the MySQL table under following columns:

ID | Menu_Name | Position | Menu_Link | Parent_ID

1 | Home | 1 | home.php | 0
2 | Menu1 | 1 | menu1.php| 0
3 | sub1 | 1 | sub1.php | 2
4 | sub2 | 2 | sub2.php | 2
5 | Contact Us | 1 |contact.php| 0

Now...
I have created the table structure in MySQL and fetched all rows using select * from dyn_menu query.
I copied query results into another array using a while loop. hence each row of the table became an element of new array.
i.e. new array is the 'array of arrays'.

The issue is...
In order to display meny items properly, I need to have the menu item exactly in the order mentioned above, however... If I add another menu item in future, it can be present anywhere in the table and it's parent/adjascent menu items might be present before or after the item.

I think...
1. Before displaying this menu structure, I need to sort this using DFS (Depth First Search) algorithm.
but...
I'm not able to sort the 'array of arrays' using DFS algo... :(

Can anybody suggest a better way? or Does anybody have sample code snippets?

Re: How to implement dynamic hierarchical menu structure?

Posted: Mon Apr 13, 2009 1:09 pm
by n00b Saibot
1. sort by Parent ID
2. create nested arrays for each Parent ID

I would Imagine something like
[
"Home",
"Menu1" => ["Sub1", "Sub2"],
"Contact Us"
]

It would be very easy to implement sub-menus after this....

Re: How to implement dynamic hierarchical menu structure?

Posted: Mon Apr 13, 2009 2:06 pm
by McInfo
Related: viewtopic.php?t=98474

Edit: This post was recovered from search engine cache.

Re: How to implement dynamic hierarchical menu structure?

Posted: Mon Apr 13, 2009 4:10 pm
by JTMarlin8
Another idea, create unique IDs for each cat and subcat

Parent categories = 1, 2, ..., 99
Sub categories = 101, 102, ..., 199
9901, 9902, ..., 9999
Sub Sub Categories = 10101, 10102, ..., 10199
= 999901, 999902, ..., 999999

etc.

Printing out menu names would be easy... just a couple for loops and liberal use of the / and % operators.

Re: How to implement dynamic hierarchical menu structure?

Posted: Wed Apr 15, 2009 6:57 am
by yogi
Thanks all,

I will try out one of these ways and let you know how it worked (& what I did)

Regards,
Yogesh