我想创建此菜单。这是一些子菜单的一个例子。
- 绿色 - 漂亮的颜色
- 太阳 - 热色
- 天空 - 自由
- 免费
- free2
如何使用最简单的子菜单示例创建此菜单?
我创建了一个数组。这是正确的方式?
$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'
]
]
];
是正确的方式吗?
期望输出
<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>
您数组'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