使用递归遍历权限树并比对路由注册表,可以找出未绑定路由的菜单节点。具体做法是加载完整的权限树数据与已注册的路由列表,在遍历每个节点时检查其路由标识是否存在于注册表中,若不存在则将其加入结果集,同时继续深入子节点进行同样的检查,最终返回所有未绑定的节点列表。

checkUnboundRoutes函数如何递归处理嵌套菜单
该函数通过接收权限树数组和路由集合作为参数,利用递归调用自身来处理每一层级的菜单。对于当前节点,先判断其是否包含路由信息且该路由不在已注册列表中,若是则标记为未绑定;随后检查是否有子菜单,若有则再次调用该函数处理子节点,并将子节点中找到的未绑定项合并到当前结果中。

$permissions = [
['id' => 1, 'name' => '首页', 'route' => 'home', 'children' => []],
['id' => 2, 'name' => '用户管理', 'route' => 'user.manage', 'children' => [
['id' => 3, 'name' => '查看用户', 'route' => 'user.view', 'children' => []],
['id' => 4, 'name' => '编辑用户', 'route' => null, 'children' => []]
]],
['id' => 5, 'name' => '系统设置', 'route' => 'system.config', 'children' => []]
];
$registeredRoutes = ['home', 'user.manage', 'user.view', 'system.config'];
function checkUnboundRoutes($tree, $registeredRoutes) {
$unbound = [];
foreach ($tree as $node) {
if (!empty($node['route']) && !in_array($node['route'], $registeredRoutes)) {
$unbound[] = $node;
}
if (!empty($node['children'])) {
$unbound = array_merge($unbound, checkUnboundRoutes($node['children'], $registeredRoutes));
}
}
return $unbound;
}
$result = checkUnboundRoutes($permissions, $registeredRoutes);
print_r($result);
预期输出:
php
Array
(
[0] => Array
( [id] => 4 [name] => 编辑用户 [route] => [children] => Array ( ) )
)
?>
如何处理空路由值与缺失子节点的情况
在遍历过程中,如果节点的 route 字段为空或不存在,应跳过绑定检查,因为这类菜单通常仅作为分组存在而不直接关联路由。同时,当子节点数组为空或未定义时,递归调用需确保不会因访问不存在的键而引发错误,可通过 isset 或 empty 进行前置判断来安全处理。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

// 补充验证:处理无子节点和空路由的场景
$testTree = [
['id' => 10, 'name' => '无路由菜单', 'route' => null, 'children' => []],
['id' => 11, 'name' => '缺失子节点键', 'route' => 'missing.key', 'children' => null]
];
$routes = ['missing.key'];
// 修改后的健壮版本
function safeCheckUnbound($tree, $routes) {
$res = [];
if (empty($tree)) return $res;
foreach ($tree as $node) {
if (!empty($node['route']) && !in_array($node['route'], $routes)) {
$res[] = $node;
}
if (!empty($node['children']) && is_array($node['children'])) {
$res = array_merge($res, safeCheckUnbound($node['children'], $routes));
}
}
return $res;
}
var_dump(safeCheckUnbound($testTree, $routes));
预期输出:
array(0) {
}
?>
基于输入中id=4节点的具体行为验证
在提供的示例数据中,id=4 的节点名为“编辑用户”,其 route 值为 null,因此它不会被判定为“未绑定路由”的菜单,而是被视为无路由的分组节点。这一行为符合权限系统中常见的设计逻辑:部分菜单仅用于视觉分组,不参与实际的路由跳转。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










