将嵌套UL限制在“嵌套类别”功能中

时间:2012-12-12 09:55:35

标签: php nested

我有一个这样的数组($ nested)(这是print_r()输出)

Array
(
    [1] => Array
        (
            [id] => 1
            [module] => 1
            [parent] => 0
            [name] => Audio
        )

    [20] => Array
        (
            [id] => 20
            [module] => 1
            [parent] => 5
            [name] => Mixer analogici
        )

    [16] => Array
        (
            [id] => 16
            [module] => 1
            [parent] => 4
            [name] => Videoproiettori
        )

    [11] => Array
        (
            [id] => 11
            [module] => 1
            [parent] => 2
            [name] => Strutture
        )

    ...

    [19] => Array
        (
            [id] => 19
            [module] => 1
            [parent] => 5
            [name] => Mixer digitali
        )

)

用于创建嵌套菜单的递归函数:

function nmenu($module, $parent, $array) {
    $has_children = false;
    foreach($array as $key => $value) {
        if ($value['module'] == $module) {  
            if ($value['parent'] == $parent) {       
                if ($has_children === false && $parent) {
                    $has_children = true;
                    echo "<ul>\n";
                }
                echo '<li>';
                echo '' . $value['name'] . " \n";
                    nmenu($module, $key, $array);
                echo "</li>\n";
            }
        }
    }
    if ($has_children === true && $parent) echo "</ul>\n";
}

我称之为:

<ul>
    <?php nmenu($row_rsNavModules['mod_id'], 0, $nested) ?>
</ul>

一切都很好,递归函数按预期工作,它创建了一系列无限嵌套的UL ......好吧,它是太多的“无限”:我想限制缩进级别(也就是数字)缩进的ULS)到2,像这样:

Cat 1
    Subcat 1-1
    Subcat 1-2
    ...
Cat 2
    Subcat 2-1
    Subcat 2-2
    ...

并不是这样结束的:

Cat 1
    Subcat 1-1
            Sub-Subcat 1-1-1
                    Sub-Sub-Subcat 1-1-1-1
                    ...

请问,如何编辑上一个功能来实现这一目标? 提前谢谢!

1 个答案:

答案 0 :(得分:1)

一旦计数器达到极限,您只需要有一个计数器并退出该功能。类似的东西:

//counter parameter added
function nmenu($module, $parent, $array, $counter) {
    $has_children = false;
    foreach($array as $key => $value) {
        if ($value['module'] == $module) {  
            if ($value['parent'] == $parent) {       
                if ($has_children === false && $parent) {
                    $has_children = true;
                    echo "<ul>\n";
                }
                echo '<li>';
                echo '' . $value['name'] . " \n";

                if($counter<2){  //added 
                    //counter parameter added
                    nmenu($module, $key, $array, $counter+1);
                } //added
                echo "</li>\n";
            }
        }
    }
    if ($has_children === true && $parent) echo "</ul>\n";
}

并称之为:

<ul>
    <?php 
       //counter parameter added 
       nmenu($row_rsNavModules['mod_id'], 0, $nested, 1) 
    ?>
</ul>