简体   繁体   中英

recursive function for dynamic multilevel menu php

I've a mysql table structure like this:

CREATE TABLE IF NOT EXISTS menu(
id INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY,
p_id INT(5), -- parent id
sort_id INT(5) NOT NULL, -- for position
title VARCHAR(50) NOT NULL,
etc ...);

data structure would be something like this:

id | p_id | sort_id | title 
1  | NULL |    1    |  root_1
2  |  1   |    1    |  sub1 of root_1
3  |  1   |    2    |  sub2 of root_1
4  | NULL |    2    |  root_2
5  |  2   |    1    |  sub1 of root_2
6  |  2   |    2    |  sub2 of root_2
7  |  3   |    1    |  sub1 of `sub2 of root_1`

I've created a php script to show up one level sub menu, but I can't make up my mind how to get other levels. I think a recursive function is needed, for example, to get sub1 of sub2 of root_1 element in this task.

If anyone has any idea how to start creating a recursive function in this situation , please advise me, thanks :)

It might be best to first turn this into a tree type structure:

Menu Top
  |
Nodes with NULL p_id
  |
Children

You could do this by creating a MenuNode class that has an array of children. You don't have to do it that way, but it will make it much easier to create a recursive function to output the menu.

function generate_menu_list($parent_id) { $result = mysql_query("SELECT * FROM menu WHERE p_id ='$parent_id' order by sort_id "); if (result) { while ($row = mysql_fetch_array($result)) {
$count = mysql_query("SELECT count(0) as cnt FROM menu_master WHERE parent_id='".$row['id']."'"); $countrow = mysql_fetch_array($count);

    echo '<li><a href="'$linktoredirect.'"><span class="fa fa-user"></span>'.$row['title '].'</a> ';

     if($countrow['cnt']>0)
     {
        echo '<ul>'; 
        $this->generate_menu_list($row['id']);  
        echo '</ul>';
     }  
     echo '</li>';
  } 
}   

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM