duanqianmou4661 2014-08-30 08:38
浏览 76
已采纳

如何从这个数组构建“ul li”列表?

I have data in an array with the following structure:

$persons = array(
    array($id, $name, $parent),
    array(2, 'John Smith', 0),
    array(3, 'Steve Martin', 2),
    array(4, 'Peter Griffin', 3),
    array(5, 'Cinder Ella', 0)
);

and I would like to get a tree like this:

<ul>
    <li>John Smith</li>
    <ul>
        <li>Steve Martin</li>
        <ul>
            <li>Peter Griffin</li>
        </ul>
    </ul>
    <li>Cinder Ella</li>
</ul>

Probably this is just as easy as 1-2-3 but I have tried everything already without success...

  • 写回答

2条回答 默认 最新

  • dongmu3269 2014-08-30 09:03
    关注

    heres a solution:

    <?php
    
    $persons = array(
    array(2, 'John Smith', 0),
    array(3, 'Steve Martin', 2),
    array(4, 'Peter Griffin', 3),
    array(5, 'Cinder Ella', 0)
    );
    
    echo "<ul>";
    printChildren($persons,0);
    echo '</ul>';
    
    function printChildren($arr,$id){
    foreach($arr as $subvalue)
            if($subvalue[2] == $id){
            echo '<li>'.$subvalue[1].'</li>';
        if(countChildren($arr,$subvalue[0])>0){
            echo '<ul>';
            printChildren($arr,$subvalue[0]);
            echo '</ul>';
        }
    }
    }
    function countChildren($arr,$id){
    $i=0;
    foreach($arr as $value){
    if($value[2] == $id) $i++;
    }
    return $i;
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码