php create navigation menu from multidimensional array dynamically(php从多维数组动态创建导航菜单)
问题描述
我对此进行了研究,但无法找到确切的答案.此处与此相关的大多数问题/答案似乎尚未完成.如果有人知道类似于我的问题的最终解决方案,请指出我的方向!
I did research on this, and wasn't able to find an exact answer. Most of the questions/answers on here pertaining to this seem to be unfinished. If anyone knows of a finished solution similar to my question, please point me in that direction!
这是我的数组:
Array
(
['home'] => Array
(
[0] => sub-home1
[1] => sub-home2
)
['about'] => Array
(
[0] => sub-about
['about2'] => Array
(
[0] => sub-sub-about
)
)
['staff'] => Array
(
[0] => sub-staff1
[1] => sub-staff2
)
['contact'] => contact
)
我想把它变成这样:
<ul>
<li><a href="">home<a/>
<ul>
<li><a href="">sub-home1</a></li>
<li><a href="">sub-home2</a></li>
</ul>
</li>
<li><a href="">about<a/>
<ul>
<li><a href="">sub-about</a></li>
<li><a href="">about2</a>
<ul>
<li><a href="">sub-sub-about<a/></li>
</ul>
</li>
</ul>
</li>
<li><a href="">staff<a/>
<ul>
<li><a href="">sub-staff1</a></li>
<li><a href="">sub-staff2</a></li>
</ul>
</li>
<li><a href="">contact<a/></li>
</ul>
数组将动态生成,但限制为 3 个级别,例如:about->about2->sub-sub-about.我尝试解决这个问题:PHP/MySQL Navigation Menu 但它们看起来并不真正得出结论?我熟悉 foreach 的 while 和 for 循环,但我似乎无法理解这个.
The array will be dynamically generated, but will have a limit of 3 levels ex: about->about2->sub-sub-about. I tried going off of this question: PHP/MySQL Navigation Menu but they didn't really seem to come to a conclusion? I am familiar with foreach's whiles and for loops but I just can't seem to wrap my head around this one.
Enzino,您的代码有效!
推荐答案
这是我的解决方案:
Here is my solution:
<?php
function MakeMenu($items, $level = 0) {
$ret = "";
$indent = str_repeat(" ", $level * 2);
$ret .= sprintf("%s<ul>
", $indent);
$indent = str_repeat(" ", ++$level * 2);
foreach ($items as $item => $subitems) {
if (!is_numeric($item)) {
$ret .= sprintf("%s<li><a href=''>%s</a>", $indent, $item);
}
if (is_array($subitems)) {
$ret .= "
";
$ret .= MakeMenu($subitems, $level + 1);
$ret .= $indent;
} else if (strcmp($item, $subitems)){
$ret .= sprintf("%s<li><a href=''>%s</a>", $indent, $subitems);
}
$ret .= sprintf("</li>
", $indent);
}
$indent = str_repeat(" ", --$level * 2);
$ret .= sprintf("%s</ul>
", $indent);
return($ret);
}
$menu = Array(
'home' => Array("sub-home1", "sub-home2"),
'about' => Array("sub-about", "about2" => Array("sub-sub-about")),
'staff' => Array("sub-staff1", "sub-staff2"),
'contact' => "contact"
);
print_r($menu);
echo MakeMenu($menu);
?>
这篇关于php从多维数组动态创建导航菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:php从多维数组动态创建导航菜单
基础教程推荐
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01