无限级分类的一种实现方式

list返回子孙树列表
 1 /**
 2  * * list返回子孙树
 3  * @param array $list 原始列表
 4  * @param int $parentId 父id
 5  * @param int $level 几级子孙
 6  * @param string $space 空格占位
 7  * @date:2017.2.17
 8  * @return array
 9  */
10 function treeList($list, $parentId = 0, $level = 0, $space = '  ')
11 {
12     static $bk = array();
13     foreach ($list as $each)
14     {
15         if ($each['parent_id'] == $parentId)
16         {
17             $each['level'] = $level;
18             $each['show'] = str_repeat($space, $level) . $each['name'];
19             $bk[$each['id']] = $each;
20             treeList($list, $each['id'], $level + 1, $space);//子孙紧跟在自己后面
21         }
22     }
23     return $bk;
24 }

 

list返回子孙树数组
 1 /**
 2  * * list返回子孙树
 3  * @param array $list 原始列表
 4  * @param int $parentId 父id
 5  * @param int $level 几级子孙
 6  * @param string $space 空格占位
 7  * @date:2017.2.17
 8  * @return array
 9  */
10 function treeArr($list, $parentId = 0, $level = 0, $space = '  ')
11 {
12     $bk = array();
13     foreach ($list as $each)
14     {
15         if ($each['parent_id'] == $parentId)
16         {
17             $each['level'] = $level;
18             $each['show'] = str_repeat($space, $level) . $each['name'];
19             $each['sonArr'] = treeArr($list, $each['id'], $level + 1, $space);
20             $bk[$each['id']] = $each;
21         }
22     }
23     return $bk;
24 }

 

如果只需要所有层级名称

/**
 * 获取所有层级名列表
 * @date:2017.2.17
 * @return array
 */
function getFulNameList()
{
    $listRaw = getList();
    $list = array();
    //一些处理
    foreach ($listRaw as $each)
    {
        $list[$each['id']] = iconvArray($each, 'GBK', 'UTF-8');//GBK->UTF-8
    }
    //加所有层级名
    foreach ($list as $id => $each)
    {
        $fulName = $list['name'];
        $parentId = $each['parent_id'];
        while ($parentId != 0 && $list[$parentId]['parent_id'] != 0)
        {
            $fulName = $list[$parentId]['name'].'_'.$fulName;
            $parentId = $list[$parentId]['parent_id'];
        }
        $list[$id]['fulName'] = $fulName;
    }
    return $list;
}

 

//获取所有子孙

 1 function getSpringId($selfId, $list)
 2 {
 3     $springIdArr = array();
 4     $parentIdArr = array($selfId => $selfId);
 5     do
 6     {
 7         $newSonArr = array();
 8         foreach ($list as $each)
 9         {
10             if (isset($parentIdArr[$each['parent_id']]))
11             {
12                 $springIdArr[$each['id']] = $each['id'];
13                 $newSonArr[$each['id']] = $each['id'];
14             }
15         }
16         $parentIdArr = $newSonArr;//新一辈父
17     } while (count($parentIdArr) > 0);
18 
19     return $springIdArr;
20 }

 

上一篇:react ~3.动态无限层级顶部菜单和左边菜单设计制作


下一篇:docker 实战---部署tomcat\weblogic集群 (二)