我正在尝试使用 PHP 创建从 MySQL 数据库中获取数据的动态多级菜单。我已经设法使用这种格式在 php 数组中订购菜单项:
-----------------------
Array
(
[1] => Array
(
[id] => 1
[ubicacion] => top_a
[nivel] => 1
[parent_id] =>
[tipo] => link
[link] => http://www.google.com
[titulo] => Google
[alias] => google_es
[children] => Array
(
[3] => Array
(
[id] => 3
[ubicacion] => top_a
[nivel] => 2
[parent_id] => 1
[tipo] => link
[link] => http://www.gmail.com
[titulo] => Gmail
[alias] => gmail
[children] => Array
(
[4] => Array
(
[id] => 4
[ubicacion] => top_a
[nivel] => 3
[parent_id] => 3
[tipo] => link
[link] => www.inbox.gmail.com
[titulo] => Inbox
[alias] => inbox_gmail
)
)
)
)
)
[2] => Array
(
[id] => 2
[ubicacion] => top_a
[nivel] => 1
[parent_id] =>
[tipo] => link
[link] => http://www.yahoo.com
[titulo] => Yahoo
[alias] => yahoo
)
)
-----------------------
问题是我无法弄清楚如何以适用于 n 级的方式将此数组输出为 HTML 标记。我可以使用固定数量的级别来做到这一点,如下所示:
foreach($menu_array as $menu) {
echo "<li><a href='{$menu['link']}'>{$menu['titulo']}</a>";
if (array_key_exists('children',$menu)) {
echo "<ul>";
foreach ($menu['children'] as $child_menu) {
echo "<li><a href='{$child_menu['link']}'>{$child_menu['titulo']}</a>";
if (array_key_exists('children',$child_menu)) {
echo "<ul>";
foreach ($child_menu['children'] as $child2_menu) {
echo "<li><a href='{$child2_menu['link']}'>{$child2_menu['titulo']}</a>";
}
echo "</ul>";
}
}
echo "</ul>";
}
echo "</li>";
}
但这仅适用于 3 个级别,我知道应该有办法解决这个问题,我知道我不是第一个面临多维数组的 HTML 输出问题的人。