gpt4 book ai didi

php - PHP多级菜单

转载 作者:可可西里 更新时间:2023-10-31 22:44:39 25 4
gpt4 key购买 nike

我有一个这样的主题表:

id
title
parent_id
full_path

full_path 用于查找父级递归。像这样:

+----+-----------+-----------+-----------+
| 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 |
+----+-----------+-----------+-----------+

我怎样才能得到这样的递归数组:

array
(
40 => array
(
42 => array
(
50,51,52,etc.
),
53,
54
)
41 => array
(
43,
55,
),
44 => array
(
57,
),
etc...
)

我可以使用 full_path 创建多级菜单吗?

最佳答案

您可以使用下面的代码来执行此操作。请记住,这是可行的,因为您的主题数组将非常小并且发生的递归将是最小的。不要在大型​​阵列上使用此方法。

<?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多级菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16545580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com