0

我有一个这样的数组($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
                    ...

请问,我该如何编辑以前的功能来实现这一点?提前致谢!

4

1 回答 1

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>
于 2012-12-12T09:59:11.830 回答