Multi level menu with PHP(PHP 多级菜单)
本文介绍了PHP 多级菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的主题表:
I have a subject table like this:
id
title
parent_id
full_path
full_path 用于以递归方式查找父级.像这样:
full_path is for finding parent as recursive. Like this:
+----+-----------+-----------+-----------+
| id | title | full_path | parent_id |
+----+-----------+-----------+-----------+
| 40 | home | 40 | 0 |
| 41 | myhome1 | 41 | 0 |
| 42 | **** | 40-42 | 40 |
| 43 | ***** | 41-43 | 41 |
| 44 | *** | 44 | 0 |
| 45 | **** | 45 | 0 |
| 46 | ***** | 46 | 0 |
| 49 | ****** | 49 | 0 |
| 50 | **** ** | 40-42-50 | 42 |
| 51 | **** ** | 40-42-51 | 42 |
| 52 | **** ** | 40-42-52 | 42 |
| 53 | ******* | 40-53 | 40 |
| 54 | **** | 40-54 | 40 |
| 55 | *** | 41-55 | 41 |
| 56 | **** **** | 40-42-56 | 42 |
| 57 | ******* | 44-57 | 44 |
+----+-----------+-----------+-----------+
我如何获得这样的递归数组:
How i can get an recursive array like this:
array
(
40 => array
(
42 => array
(
50,51,52,etc.
),
53,
54
)
41 => array
(
43,
55,
),
44 => array
(
57,
),
etc...
)
我可以使用 full_path 来创建多级菜单吗?
Can I use full_path for create multilevel menu?
推荐答案
您可以使用下面的代码来执行此操作.请记住,这是有效的,因为您的主题数组将非常小并且发生的递归将是最小的.不要在大型数组上使用这种方法.
You could use the code below to do this. Keep in mind that this works because your subjects array will be very small and the recursion that happens will be minimal. Dont use this approach on large arrays.
<?php
$query = "SELECT id, parent_id FROM subjects";
//execute with your prefered method, eg mysqli
$rows = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rows[] = $row;
}
function getChildren($p) {
global $rows;
$r = array();
foreach($rows as $row) {
if ($row['parent_id']==$p) {
$r[$row['id']] = getChildren($row['id']);
}
}
return $r;
}
$final = getChildren(0);
?>
这篇关于PHP 多级菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:PHP 多级菜单
基础教程推荐
猜你喜欢
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
