简体   繁体   English

如何在递归树函数(PHP)中显示索引(#行号)

[英]How to show index (# Line Number) inside a recursive tree function (PHP)

I would like to be able to print the index inside a recursive function and I don't really understand why it's not working... I'm able to print a table in the right order, but the counter is not working well ??? 我希望能够在递归函数中打印索引,但我真的不明白为什么它不起作用...我能够以正确的顺序打印表,但是计数器工作不正常? ? Every time it print a line, it should add one to the counter, but it's not really what's happening here... I'm a little confused over the recursion here. 每次打印一行时,都应该在计数器上添加一行,但这并不是这里真正发生的事情……对于这里的递归,我有些困惑。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Here's the basic code example: 这是基本的代码示例:

function outputMenu ($menu_tree, $cpt = 0) {
    $html = "";
    foreach ($menu_tree as $menu) {
        $cpt++;
        $html .= $cpt .'- '. $menu["name"]."<br>";
        if (count($menu['children']) > 0) {
            $html .= outputMenu ($menu["children"], $cpt);
        }               
    }
    return $html;
}
outputMenu($menu_tree);

And the results: 结果:

1- ablato 1-阿拉博托
2- Malone 2-马龙
3- |--- the skulls 3 3- | ---头骨3
4- |--- Titanic 4- | ---泰坦尼克号
3- Uno test 3- Uno测试
4- |--- Alien Quadrilogie 4- | ---外星人四方
5- |------ aliens are back 5- | ----------外星人回来了
6- |------ Prison Break 6- | ------越狱
7- |--------- 24 Hours 7- | --------- 24小时
8- |------------ Marvels Agents of Shield 8- | ------------盾牌奇迹特工
7- |------ the skulls 7- | ------头骨
5- |--- Evasion 5- | ---逃避
6- |--- star wars 6- | ---星球大战

Since it's a recursive function you will leave the foreach loop once you have children in your variable, sending the current index. 由于它是一个递归函数,一旦您在变量中有子级,您将离开foreach循环,发送当前索引。 Therefore you have values 3, 4 for the first children of number 2 and then you will once again continue the foreach with the value 3. 因此,对于第2个数字的第一个孩子,您具有值3、4,然后您将再次使用值3继续foreach。

A simple solution would be using a variable outside your function. 一个简单的解决方案是在函数外部使用变量。

Thanks, I have followed you lead using a global variable outside the function and I added 谢谢,我跟随您带领在函数外使用全局变量,并添加了

$menu_index = 0;

function outputMenu ($menu_tree) {
    global $menu_index;
    $html = "";
    foreach ($menu_tree as $menu) {
        $menu_index++;
        $html .= $menu_index .'- '. $menu["name"]."<br>";
        if (count($menu['children']) > 0) {
            $html .= outputMenu ($menu["children"]);
        }               
    }
    return $html;
}
outputMenu($menu_tree);

at the beginning of my function and it's now working perfectly. 在我的功能开始时,它现在运行良好。 Big thanks :) 太谢谢了 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM