以下是我所拥有的:
$nav = array (
"page 1" => array (
"page 1.1" => array (
"page 1.1.1"
"page 1.1.2"
) ,
"page 1.2"
)
"page 2" => array (
"page 2.1"
)
);
这就是我想要的:
<nav>
<ul>
<li>page 1
<ul>
<li>page 1.1
<ul>
<li>page 1.1.1</li>
<li>page 1.1.2</li>
</ul>
</li>
<li>page 1.2</li>
</ul>
</li>
<li>page 2
<ul>
<li>page 2.1</li>
</ul>
</li>
</ul>
</nav>
到目前为止我所拥有的:
foreach ($nav as $key => $val) {
if (!is_numeric($key)) {
$nav_entry = $key;
} else {
$nav_entry = $val;
}
echo "<li>" . $nav_entry . "</li>";
}
我的问题是,如果存在子数组,我需要有foreach循环。最重要的是,我需要以某种方式放入if
语句,以添加<ul></ul>
标记。。。
我开始看到星星。。。太令人困惑了。
试试:(
function createMenu($nav){
echo "<ul>";
foreach($nav as $key => $row){
if(!is_array($row)){
echo "<li>".$row."</li>";
}else{
echo "<li>".$key;
createMenu($row);
echo "</li>";
}
}
echo "</ul>";
}
createMenu($nav);
尝试
<?php
$nav = array (
"page 1" => array (
"page 1.1" => array (
"page 1.1.1",
"page 1.1.2"
),
"page 1.2"
),
"page 2" => array (
"page 2.1"
)
);
function drawRecursive($list){
echo "<ul>";
foreach ($list as $key=>$item){
echo "<li>";
if (is_array($item)){
echo $key;
drawRecursive($item);
} else {
echo $item;
}
echo "</li>";
}
echo "</ul>";
}
echo "<nav>";
drawRecursive($nav);
echo "</nav>";
?>
$array = [
'home',
'page 1' => [
'page 1.1' => [
'page 1.1.1',
'page 1.1.2'
],
'page 1.2'
],
'page 2' => [
'page 2.1'
]
];
function buildLists($array) {
$result = '';
foreach($array as $key => $value) {
if(!is_int($key)) {
$result .= '<li>' . $key;
} else if(!is_array($value)) {
$result .= '<li>' . $value;
}
if(is_array($value)) {
$result .= '<ul>';
$result .= buildLists($value);
$result .= '</ul>';
} else {
$result .= '</li>';
}
}
return $result;
}
用法:
<nav>
<ul>
<?= buildLists($array); ?>
</ul>
</nav>
输出:
<li>home</li>
<li>page 1
<ul>
<li>page 1.1
<ul>
<li>page 1.1.1</li>
<li>page 1.1.2</li>
</ul>
</li>
<li>page 1.2</li>
</ul>
</li>
<li>page 2
<ul>
<li>page 2.1</li>
</ul>
</li>