First we need a database source holding the information for our navigation menu:
Next we have to add some data for our menu: menu items and sub-menu items.
Example: our menu item "Products" will have several sub-menu items and the record id is a "2"
All submenu items need the number "2" as value for the parent_id. The parent_id for each main menu item is a "0" (zero).
In following code block we are building a database result and put the value into two multi-dimensional arrays:
$parent_menu and $sub_menu
The $parent_menu array is holding the label, the link (URL) and a count value that we need to decide if there is a sub-item or not. The $sub_menu is holding the label and link values and the value of the parent_id.
We are looping through the database record set for records where the parent_id is a "0" or not. If the value equal to "0" it's a parent record and otherwise it's a sub-item record.
For the creation of the whole navigation bar we group the whole code into a function, this way it's more portable and we can accesses the code several times in one script without to repeat the code.
The arguments of the function are the both arrays, the name of the query string value that's used to fold out the menu, the two ids used to identify the unordered lists with the CSS style and an extra name for some CSS pseudo class to give a main link element with sub-items a different look.
A nested unordered list is a list with list items ("li" elements) and several other lists ("ul" elements). A main can hold another lists or new "ul" elements.
To do this we start in our function with a "ul" element, to identify the element with CSS we add some id attribute here.
Inside the loop there is a test for the count value from parent items, if the count is not null the menu item querystring value is added.
Now the real code begins with this test for a request value send via the link from a parent menu item a new loop is opened to create a list with sub-items related to the parent item. Inside the statement the function "rebuild_link: is called, this function is used to handle the query string:
The arguments for this function are the link from the array, the variable name and value from the parent menu item (to keep the list open). Inside the function the query string will be exploded and is getting rebuilt without becoming in trouble with existing parts or new variables. At the end the function will return a modified link with all parts of the query string.
How to use this function? It's easy just echo the function name like here:
Don't forget to try our PHP demo for better understanding.