doucuoyan0426 2013-04-27 15:04
浏览 7
已采纳

php使用子项循环未定义的项目大小

So as an example I have this structure with pages in a website. The thing is I have to get these items in a dropdown list, but they have to intend based on their parent.

  • loadSubItems(id) returns the subitems for the id.
  • loadSubItems(0) will give the subitems from the root, which in this case is 9, 16, 20
  • loadSubItems(9) will give an empty array loadSubItems(16) will return 17, 18, 19

The problem is that the middle loop (the foreach) has to keep on looping as long as there are subitems for that level, print them and for each level an extra intend "_" has to be added.

I have been trying to solve this for hours and I've lost my thinking and I can't seem to figure out what has to happen to be able to do this.

Any help is welcome! Thanks in advance:

Testdata below:

https://dl.dropboxusercontent.com/u/10123290/structuur.png

I'm using the following code to go to the second level:

    $items = loadSubItems(0); // returns 9 16 20
    $intend = "";
    foreach($items as $item) {
        $subitems = loadSubItems($item); 
        if(count($subitems) > 0) {
            echo $intend.$item." has subitems: <br />";
            $intend .= "_";
            foreach($subitems as $subitem) {
                echo $intend.$subitem."<br />";
            }
        } else {
            echo "<br />".$item." has no subitems <br />";
        }
    }

This code has output:

9 has no subitems 
16 has subitems: 
_17
_18
_19

20 has no subitems 

edit: So what I want as a result would be:

9 has no subitems 
16 has subitems: 
_17
__21
___22
__23
___24
_18
_19

20 has no subitems
  • 写回答

1条回答 默认 最新

  • dsv73806 2013-04-27 15:32
    关注

    Check out this little function I wrote. It does exactly what you need.. This is the recursive method. You can check it out for any levels.

    <?php
    function arrayRec($array, $intent) {
        $intent .= "_";
        foreach($array as $key=>$value) {
            echo $intent.$key."</br>";
            arrayRec($value, $intent);
        }   
    }
    $tree = array("1" => array("11" => array(), "12" => array(), "13" => array()), "2" => array(), "3" => array("31" => array("311" => array()), "32" => array()), "4");
    arrayRec($tree);
    ?>
    

    This results in something like:

    _1
    __11
    __12
    __13
    _2
    _3
    __31
    ___311
    __32
    _4
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100