无限极分类实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 递归
*/
public function getTree($data, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
{
$tree = array();
foreach($data as $k => $v) {
if($v[$pid] == $root) {
//父亲找到儿子
$v[$child] = $this->getTree($data, $pk, $pid, $child, $v[$pk]);
$tree[] = $v;
}
}
return $tree;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 迭代
*/
public function getTree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
{
$tree = array();
$packData = array();
foreach ($list as $data) {
$packData[$data[$pk]] = $data;
}
foreach ($packData as $key => $val) {
if ($val[$pid] == $root) {
//代表跟节点
$tree[] = &$packData[$key];
} else {
//找到其父类
$packData[$val[$pid]][$child][] = &$packData[$key];
}
}
return $tree;
}
LeoQin wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
0%