用于动态多级菜单php的递归函数 [英] recursive function for dynamic multilevel menu php
问题描述
我有一个 mysql
这样的表结构:
CREATE TABLE IF NOT EXISTS菜单(
id INT(5)NOT NULL AUTO_INCREMENT PRIMARY KEY,
p_id INT(5), - parent id
sort_id INT(5)NOT NULL, - 位置
title VARCHAR(50)NOT NULL,
etc ...);
数据结构就像这样:
id | p_id | sort_id | title
元素的子2的
1 | NULL | 1 | root_1
2 | 1 | 1 | root_1
3 |的子1 1 | 2 | root_1
4 |的子2 NULL | 2 | root_2
5 | 2 | 1 | root_2
6 |的子1 2 | 2 | root_2
7 |的子2 3 | 1 |我已经创建了一个php脚本来显示一个级别的子菜单,但我无法决定如何获得其他关卡。我认为需要递归函数,例如,在本任务中获取root_1sub1。
如果有人知道如何在这种情况下开始创建递归函数,请告诉我,谢谢:)
解决方案最好先将其转换为树型结构:
菜单顶部
|
使用NULL p_id
|的节点
Children
您可以通过创建一个具有子组数的MenuNode类来实现此目的。您不必这样做,但它会使创建递归函数输出菜单变得更加容易。
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.
这篇关于用于动态多级菜单php的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!