我要创建此菜单。这是带有一些子菜单的示例。
如何用最简单的子菜单示例创建此菜单?
我创建了一个数组。这是正确的方法吗?
$NavMenu = [
'The Green' =>
[
'name' => 'The Green',
'subname' => 'Nice Color',
'href' => 'greenlink',
'title' => 'green is nature',
'icon' => 'globe',
'class' => 'green',
'subnav' => ''
],
'The Sun' =>
[
'name' => 'The Sun',
'subname' => 'hot color',
'href' => 'yellowlink',
'title' => 'yellow is sun',
'icon' => 'sunicon',
'class' => 'yellow',
'subnav' => ''
],
'The Sky' =>
[
'name' => 'The Sky',
'subname' => 'freedom',
'href' => 'bluelink',
'title' => 'blue is cold',
'icon' => 'free',
'class' => 'yellow',
'subnav' =>
[
'name' => 'Free',
'href' => 'bluelinkFree',
'title' => 'freedom is love',
'class' => 'blueFreedom'
],
[
'name' => 'Free2',
'href' => 'bluelinkFree2',
'title' => 'freedom is love2',
'class' => 'blueFreedom2'
]
]
];
foreach是否正确?
期待输出
<ul>
<li>
<a class="green" href="greenlink" title="green is nature">
<span icon="globe"></span>The Green - Nice Color</a>
</li>
<li>
<a class="yellow" href="yellowlink" title="yellow is sun">
<span icon="sunicon"></span>The Sun - hot color</a>
</li>
<li>
<a class="blue" href="bluelink" title="blue is cold">
<span icon="free"></span>The Sky - freedom</a>
<ul>
<li>
<a class="blueFreedom" href="bluelinkFree" title="freedom is love">Free</a>
</li>
<li>
<a class="blueFreedom2" href="bluelinkFree2" title="freedom is2 love">Free2</a>
</li>
</ul>
</li>
</ul>
答案 0 :(得分:0)
数组'subnav' => 'Free' =
的这一部分无效php。
还要注意,要创建的子菜单缺少诸如subname
和icon
之类的数组键。
您可以使用单个foreach
并检查键subnav
的键是否包含数组:
echo "<ul>";
foreach ($NavMenu as $navItem) {
echo sprintf(
'<li><a class="%s" href="%s" title="%s"><span icon="%s"></span>%s - %s</a>',
$navItem["class"],
$navItem["href"],
$navItem["title"],
$navItem["icon"],
$navItem["name"],
$navItem["subname"]
);
if (is_array($navItem["subnav"])) {
$subNavItem = $navItem["subnav"];
echo sprintf(
'<ul><li><a class="%s" href="%s" title="%s"><span icon="%s"></span>%s - %s</a></li></ul>',
$subNavItem["class"],
$subNavItem["href"],
$subNavItem["title"],
$subNavItem["icon"],
$subNavItem["name"],
$subNavItem["subname"]
);
}
echo "</li>";
}
echo "</ul>";
查看Php demo