I'm trying to work my way with PHP and create a PHP menu that uses items stored in database and a PHP code to construct the menu items in the right order. The values on the database can be changed so i want to keep the parent items exported first then the nested items added below.
I want to use a loop (do-while? i guess) to get the data from the database so i can get the menu arranged correctly with the nested items and outputted with a class that I want to use.
My database table stores the title and url for each item and the nested items contain the id of the parent items, the parent items has id 0 set as parent and it looks like this:
- --------------------
- | id | int(11) |
- --------------------
- | title | varchar |
- --------------------
- | url | varchar |
- --------------------
- | parent | int(11) |
- --------------------
Here is my PHP code:
- try {
- $stm = $db->prepare('SELECT * FROM menu');
- $stm->execute();
- $result = $stmt->fetchAll();
-
- // requested loop / function
-
- }
The output should look like this:
- $menu = menu::create()
- ->add('Homepage', '/', menu::create()
- ->add('Item1', '/item1/', menu::create()
- ->add('Subitem1', '/subitem1/')
- ->add('Subitem1', '/subitem1/')
- ->add('Item2', '/item2/', menu::create()
- ->add('Subitem3', '/subitem3/')
- ->add('Subitem4', '/subitem4/')
Please suggest how to get this output with the database items... Thank you.