【问题标题】:increment $x across multiple nesting loops在多个嵌套循环中增加 $x
【发布时间】:2015-05-21 17:25:02
【问题描述】:

为了列出我网站上的所有类别,我使用以下函数遍历类别层次结构:

$x = 1;
function list_categories($categories, $x) {
    foreach($categories as $category) {
        $cat_list .= '<li>'.$category['name'].'<li>';
        if (count($category['children']) > 0) {
            $cat_list .= '<ul>'
            list_categories($category['children'], $x);
            $cat_list .= '</ul>'
        }
        $x++; // incremention of $x
    }
}

问题是$x按以下方式递增:

// ITERATION #1
parent: $x = 1
|   // nesting loop #1
|--> child $x = 2
    |   // sub-nesting loop #1
    |--> descendant $x = 3

// ITERATION #2
parent: $x = 2
|   // nesting loop #2
|--> child $x = 3
    |   // sub-nesting loop #2
    |--> descendant $x = 4

// ITERATION #3
parent: $x = 3
|   // nesting loop #3
|--> child $x = 4
    |   // sub-nesting loop #3
    |--> descendant $x = 5

如何使$x 在所有父循环和嵌套循环中以直线顺序递增(例如 1、2、3、4、5、6、7、8、9、10)?

【问题讨论】:

    标签: php loops foreach nested-loops


    【解决方案1】:

    您需要将$x 设为引用参数,以便在函数中分配它会更新调用者的变量。

    function list_categories($categories, &$x) {
    

    【讨论】:

    • 我刚试了下,报错:call-time pass-by-reference has been removed
    • 我认为你不应该从我的零钱中得到这些。见stackoverflow.com/questions/8971261/…
    • 如果你写了list_categories ($category['children'], &amp;$x);,你会得到那个错误
    • @dmit 调用函数时,不要使用&amp;$x 调用函数。定义函数时只能使用&amp;$x
    【解决方案2】:

    通过您对函数的调用传递 $x。

    list_categories($category['children']); 应该将 $x 作为参数传递。

    【讨论】:

    • 对不起,我忘了写在我的问题中。我已经在我的应用程序中这样做了。我已经编辑了帖子中的代码。
    • 如果他不这样做,他会因为传递错误数量的参数而出错。
    • 查看另一个答案 - 它需要通过引用传递。
    • @Barmar - 这正是我在他进行编辑之前查看问题时立即注意到的。在我能够更新以添加 &amp; 以使变量成为引用之前,我看到您添加了您的答案。对不起。
    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 2017-03-26
    • 1970-01-01
    • 2013-08-04
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多