具有该数据结构的递归菜单

时间:2016-04-20 10:19:36

标签: php recursion menu

我正在学习递归,这里是菜单数组,我搜索了很多,但找不到具有该菜单结构的解决方案。

任何人都可以帮助解决这些问题。

$menu = array(
    'level' => array(
        0 => 1
        1 => 1
        2 => 2
        3 => 3
        4 => 1
        5 => 2
        6 => 2
        7 => 3
        8 => 2
    ),
    'title' => array(
        0 => title 1
        1 => title 2
        2 => title 3
        3 => title 4
        4 => title 5
        5 => title 6
        6 => title 7
        7 => title 8
        8 => title 9
    )
)

如何使用递归生成以下html结构?

<ul>
    <li>title 1</li>
    <li>title 2
        <ul>
            <li>title 3
                <ul>
                    <li>title 4</li>
                </ul>
            </li>
        </ul>
    </li>
    <li>title 5
        <ul>
            <li>title 6</li>
            <li>title 7
                <ul>
                    <li>title 8</li>
                </ul>
            </li>
            <li>title 9</li>
        </ul>
    </li>
</ul>

1 个答案:

答案 0 :(得分:-1)

我合并了结构和级别。递归函数创建输出。 我认为这段代码很容易理解 - 不需要评论。 结构只是将数组的第一个元素作为标题并增加级别。

<?php
$menu = [
    'title 1',
    [
        'title 2',
        [
            ['title 3',
            'title 4']
        ]
    ],
    [
        'title 5',
            'title 6',
            ['title 7',
            'title 8'],
            'title 9'
    ]
];

function createMenu($menu,$entry = false,$level = 1) {
    foreach ($menu as $title) {
        if (is_array($title)) {
                createMenu($title,true,$level);
                if (count($title)>1) {
                echo str_repeat("\t",$level*2-1)."\t</ul>\n";
                echo str_repeat("\t",$level*2-1)."</li>\n";
                }
        } else {
            echo str_repeat("\t",$level*2-1)."<li>$title";
            if ($entry) {
                echo "\n".str_repeat("\t",$level*2-1)."\t<ul>\n";
                $level++;
                $entry = false;
            } else {
                echo "</li>\n";
            }
        }
    }
}
echo "<ul>\n";
createMenu($menu);
echo "</ul>";

解决方案2坚持你的问题,即使我不推荐它:

<?php
$menu = array(
    'level' => [1,1,2,3,1,2,2,3,2],
    'title' => ["title 1","title 2","title 3","title 4","title 5","title 6","title 7","title 8","title 9"]
);
echo "<ul>\n";
//cycle levels
$lastLevel = 1;
foreach ($menu['level'] as $key => $level) {
    if ($key == 0) {}
    elseif ($level > $lastLevel) echo "\n".str_repeat("\t",$lastLevel*2)."<ul>\n";
    elseif ($level < $lastLevel) {
        echo "</li>\n";
        for (;$level<$lastLevel;$lastLevel--) {
            echo str_repeat("\t",($lastLevel-1)*2)."</ul>\n";
            echo str_repeat("\t",($lastLevel-1)*2-1)."</li>\n";
        }
    } else echo "</li>\n";
    echo str_repeat("\t",$level*2-1).'<li>'.$menu['title'][$key];
    $lastLevel = $level;
}
echo "</li>\n";
//finish tags
for (;1 < $lastLevel;$lastLevel--) {
    echo str_repeat("\t",($lastLevel-1)*2)."</ul>\n";
    echo str_repeat("\t",($lastLevel-1)*2-1)."</li>\n";
}
echo '</ul>';