list返回子孙树列表
1 /**
2 * * list返回子孙树
3 * @param array $list 原始列表
4 * @param int $parentId 父id
5 * @param int $level 几级子孙
6 * @param string $space 空格占位
7 * @date:2019.06.20
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:2019.06.20
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:2019.06.20
* @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 }
//提供一个无限极分类的方法 public static function list_level($data,$pid=0,$level=0) { //定义一个静态变量,存储一个空数组,用静态变量,是因为静态变量不会被销毁, //会保存之前保留的值,普通变量在函数结束时,会死亡,生命周期函数开始到函数结束,再次调用重新开始生长 //保存一个空数组 static $array=[]; foreach($data as $k=>$v){ //进行判断如果pid=0,那么为顶级父类,放入定义的空数组里 if($pid==$v['pid']){ //添加空格进行分层 $v['level']=$level; $array[]=$v; //递归点,调用自身,把顶级父类的主键id作为父类进行再调用循环,空格+1 self::list_level($data,$v->id,$level+1); } } return $array; }