php 无限分类递归树形(稳定版)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jayhkw/article/details/68947135
array(4) {
  [0] => array(4) {
    ["id"] => int(3)
    ["name"] => string(6) "餐厅"
    ["pid"] => int(1)
    ["sort"] => int(50)
  }
  [1] => array(4) {
    ["id"] => int(2)
    ["name"] => string(6) "建材"
    ["pid"] => int(0)
    ["sort"] => int(50)
  }
  [2] => array(4) {
    ["id"] => int(1)
    ["name"] => string(6) "家居"
    ["pid"] => int(0)
    ["sort"] => int(50)
  }
  [3] => array(4) {
    ["id"] => int(4)
    ["name"] => string(6) "客厅"
    ["pid"] => int(1)
    ["sort"] => int(50)
  }
}

函数

function genTree($items,$pid ="pid") {

    $map  = [];
    $tree = [];   
    foreach ($items as &$it){ $map[$it['id']] = &$it; }  //数据的ID名生成新的引用索引树
    foreach ($items as &$it){
        $parent = &$map[$it[$pid]];
        if($parent) {
            $parent['son'][] = &$it;
        }else{
            $tree[] = &$it;
        }
    }
    return $tree;
}

map, tree的前置申明,可以删除。

今天闲着无事,对网上的一大堆 无限树形递归分类方法。都觉得不好用。要不就是ID乱序有问题。反正就是不稳定,然后重新以小白的形式写了一下。先是写了一个javascript无限递归树形分类,然后移值到php中

思路

  • 1 .第二句 用原始数据 以ID的形式,生成新的索引树..
    要点:需要熟悉数组的引用方式。我的$map数据里面的数据,是以引用的方式,赋值的。也就是说修改map的数据会影响到原始数据
foreach ($items as &$it){ $map[$it['id']] = &$it; }
  • 2.有了第二句第三名就很好理解了
    循环遍历原始数据
    在map里面查找每一项的pid父级对应的项,这里新生成了一个$parent变量

注意:$parent变量值,是在map当中查找到之后,以引用的方式赋值的

foreach ($items as &$it){
        $parent = &$map[$it[$pid]];
        if($parent) {
            $parent['son'][] = &$it;
        }else{
            $tree[] = &$it;
        }
    }
  • 找到对应的pid项,引用过来后,判断此项是否存在
    也就是说如果,父级项存在,我们就在此父级项$parent中写入 son字数据

这个子数据就是当前遍历的项,当我们往$parent加入数据之后,其实map里面的数据也在改变
最后如果判断的parent父级项不存在,那个直接添加到tree结果中。

注意:在给$tree写入数据时,你们也能注意到,是以引用的方式.

同时贴上我的另一篇博客

javascript分类树 http://blog.csdn.net/jayhkw/article/details/68945087

猜你喜欢

转载自blog.csdn.net/jayhkw/article/details/68947135