为了构建痕迹导航菜单,我需要将数组$exampleBreadcrumbMenu
转换为$exampleFlatArray
的形式。
基本上我需要在每条路径之后尽可能地遍历$exampleBreadcrumbMenu
,为每个菜单项构建一个数组项,并为我找到的每个菜单项创建$exampleFlatArray
中的信息。
我的递归工作得很好,所以我可以处理树结构中的每个项目,但无法弄清楚如何为每个项目维护正确的级别编号。
主要代码位于$page->remap_breadcrumbmenu_to_flat_array()
下方的主要功能中。
$exampleBreadcrumbMenu = ['Home' =>
[
'Projects' => [
'Create Project',
'View Project',
'Delete Project',
'Export Project',
['Advanced' => [
'Upgrade',
'Downgrade'
]
]
],
'Employees' => [
'Create Employee',
'View Employee',
'Delete Employee',
'Export Employee',
['Advanced' => [
'Upgrade',
'Downgrade'
]
]
],
'Settings' => [
['Front End' => [
'CSS',
'HTML',
'Colors'
]
],
['Back End' => [
'Database',
'PHP',
'Colors'
]
]
],
'About',
'Help'
]
];
$exampleFlatArray = [
['home' => [
'level' => 0,
'title' => 'Home',
'prelinks' => [],
'sublinks' => [
['projects' => 'Projects'],
['employees' => 'Employees'],
['settings' => 'Settings']
]
]
],
['projects' => [
'level' => 1,
'title' => 'Projects',
'prelinks' => [
['home' => 'Home']
],
'sublinks' => [
['createProject' => 'Create Project'],
['viewProject' => 'View Project'],
['deleteProject' => 'Delete Project'],
['exportProject' => 'Export Project'],
['advanced' => 'Advanced']
]
]
],
etc.,
etc.,
];
这是我到目前为止所拥有的:
public function remap_breadcrumbmenu_to_flat_array($breadcrumbMenu, $key = '', $level = 0) {
$flatArray = [];
if (is_array($breadcrumbMenu)) {
$key = $key == '' ? 'Home' : $key;
echo 'MENU>>>>>>>>>>>>>>>>> ' . $key . ' (' . $level . ')<br/>';
if (count($breadcrumbMenu) > 0) {
foreach ($breadcrumbMenu as $key => $breadcrumbItem) {
$this->remap_breadcrumbmenu_to_flat_array($breadcrumbItem, $key, ++$level);
}
}
} else {
if(is_string($breadcrumbMenu)) {
echo $breadcrumbMenu . ' (' . $level . ')<br/>';
}
}
}
递归似乎工作正常,但水平不对:
MENU>>>>>>>>>>>>>>>>> Home (0) MENU>>>>>>>>>>>>>>>>> Projects (1) Create Project (2) View Project (3) Delete Project (4) Export Project (5) MENU>>>>>>>>>>>>>>>>> Advanced (6) Upgrade (7) Downgrade (8) MENU>>>>>>>>>>>>>>>>> Employees (2) Create Employee (3) View Employee (4) Delete Employee (5) Export Employee (6) MENU>>>>>>>>>>>>>>>>> Advanced (7) Upgrade (8) Downgrade (9) MENU>>>>>>>>>>>>>>>>> Settings (3) MENU>>>>>>>>>>>>>>>>> Front End (4) CSS (5) HTML (6) Colors (7) MENU>>>>>>>>>>>>>>>>> Back End (5) Database (6) PHP (7) Colors (8) About (4) Help (5)
答案 0 :(得分:0)
不要使用++$level
,因为它还会增加当前级别范围内的局部变量,这意味着您的$level
循环的每次迭代都会增加foreach
在同一范围内。将$level + 1
传递给递归调用。