我有一个title
和children
索引的数组。
title
始终不为空。 children
是一个数组,空或非空。
任何children
都有title
和children
等等。
$myArray = [
0 => [
'title' => 'N1',
'children' =>
[
0 =>
[
'title' => 'N11',
'children' =>
[
0 =>
[
'title' => 'N111',
'children' => [],
],
],
],
],
],
1 =>
[
'title' => 'N2',
'children' =>
[
0 =>
[
'title' => 'N21',
'children' =>
[],
],
],
],
];
现在,我想创建一个包含此数组的下拉菜单。
我在从这个数组创建无序列表(ul
,li
)时遇到问题。
我希望我的结果如下:
<ul>
<li>N1
<ul>
<li>N11
<ul>
<li>N111</li>
</ul>
</li>
</ul>
</li>
<li>N2
<ul>
<li>N21</li>
</ul>
</li>
</ul>
答案 0 :(得分:11)
我确信这会奏效:
function menu($arr) {
echo "<ul>";
foreach ($arr as $val) {
if (!empty($val['children'])) {
echo "<li>" . $val['title'];
menu($val['children']);
echo "</li>";
} else {
echo "<li>" . $val['title'] . "</li>";
}
}
echo "</ul>";
}
答案 1 :(得分:2)
假设这是你的数组
$menu = array(
array(
'title'=>'N1',
'children'=>array(
'title'=>'N11',
'children'=>array(
'title'=>'N111',
'children'=>array(),
),
),
),
array(
'title'=>'N2',
'children'=>array(
'title'=>'N21',
'children'=>array(),
)
),
);
您可以使用递归来构建此HTML结构。
function createMenu($arr){
$str = '';
if(is_array($arr)){
$str .= "<li>".$arr['title'];
if(!empty($arr['children'])){
$str .="<ul>";
$str .= createMenu($arr['children'],$str);
$str .="</ul>";
}
$str .= "</li>";
}
return $str;
}
现在调用递归函数来创建HTML
$myMenu ='';
foreach($menu as $arr){
$myMenu .= createMenu($arr);
}
echo "<ul>".$myMenu."</ul>";
exit();
答案 2 :(得分:0)
我必须实现类似的功能,但我希望HTML生成位于twig模板中。这看起来像这样:
{% macro printMenuElements(nestedListElements, level = 0, parent = 'root') %}
<ul>
{% for nestedElement in nestedListElements %}
{% set children = nestedElement.children %}
{% set title = nestedElement.title %}
{% if children is not empty and children is iterable %}
<li data-parent="{{ parent }}">
{{ title }}
{{ _self.printMenuElements(children, level +1, title) }}
</li>
{% else %}
<li data-parent="{{ parent }}">
{{ title }}
</li>
{% endif %}
{% endfor %}
</ul>
{% endmacro %}
{% block body %}
<h1>Menu</h1>
{% import _self as helper %}
{{ helper.printMenuElements(yourArray) }}
{% endblock %}
生成HTML输出:
<ul>
<li data-parent="root">
N1
<ul>
<li data-parent="N1">
N11
<ul>
<li data-parent="N11">
N111
</li>
</ul>
</li>
</ul>
</li>
<li data-parent="root">
N2
<ul>
<li data-parent="N2">
N21
</li>
</ul>
</li>
</ul>
&#13;