JS与PHP递归的区别

<?php
$areas=[
    ['id'=>1,'pid'=>0,'name'=>'中国'],
    ['id'=>2,'pid'=>1,'name'=>'山东省'],
    ['id'=>3,'pid'=>1,'name'=>'北京市'],
    ['id'=>4,'pid'=>2,'name'=>'济南市'],
    ['id'=>5,'pid'=>4,'name'=>'历下区'],
    ['id'=>6,'pid'=>2,'name'=>'临沂市'],
    ['id'=>7,'pid'=>6,'name'=>'郯城县'],
    ['id'=>8,'pid'=>6,'name'=>'沂水县'],
];

function tree($id,&$item){
    global $areas;
    foreach ($areas as $area){
        if(!isset($area['child'])){
            $area['child']=[];
        }
        if($area['pid']==$id){
            $item[]=$area;
            tree($area['id'],$item[count($item)-1]['child']);
            if(empty($item[count($item)-1]['child'])){
                unset($item[count($item)-1]['child']);
            }
        }
    }
}
tree(0,$items);
<script>
    let areas=<?php echo json_encode($areas)?>;
    function tree(pid,$items){
        areas.forEach(item => {
            if (pid === item.pid) {
                let child = {
                    value: item.id,
                    label: item.name,
                    children: [],
                }
                $items.push(child)
                this.tree(item.id, child.children)
                if (child.children.length === 0) {
                    delete child.children
                }
            }
        })
    }
    let items=[]
    tree(0,items)
    console.log(items)
</script>

今天想用js的方式写个递归,后来就是不行。。。。
看来是有差别的。。。。。

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1

js用引用吗?没记错的话,你写的js要成功在vue或者其他前端框架下使用才会有效

4年前 评论
xieruidong521 (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!