无限级分类在web项目中应用非常广泛,比如商品分类、权限节点、组织架构等等。
下面介绍两种将二维数组整理成无限级树形结构的方法:
数据如下:
$data = [
["id"=>1,"pid"=>0,"name"=>"服饰"],
["id"=>2,"pid"=>0,"name"=>"电子"],
["id"=>3,"pid"=>0,"name"=>"食品"],
["id"=>4,"pid"=>1,"name"=>"男装"],
["id"=>5,"pid"=>4,"name"=>"裤子"],
["id"=>6,"pid"=>2,"name"=>"电脑"],
["id"=>7,"pid"=>6,"name"=>"笔记本电脑"],
["id"=>8,"pid"=>2,"name"=>"手机"]
];
一.递归法:
function getTree($data, $pid = 0)
{
$tree = [];
foreach ($data as $k => $v)
{
if ($v['pid'] == $pid)
{
unset($data[$k]);
$v['child'] = getTree($data, $v['id']);
$tree[] = $v;
}
}
return $tree;
}
$tree = getTree($data);
二.引用法(效率更高):
function getTree($data){
$list=[];
foreach ($data as $v){
$id=$v['id'];
$list[$id]=$v;
}
$tree=[];
foreach ($list as $k=>$v){
$pid=$v['pid'];
if(isset($list[$pid])){
$list[$pid]['child'][]=&$list[$k];
}else{
$tree[$v['id']]=&$list[$k];
}
}
return $tree;
}
$tree = getTree($data);
输出(JSON)如下:
[
{
"id": 1,
"pid": 0,
"name": "服饰",
"child": [
{
"id": 4,
"pid": 1,
"name": "男装",
"child": [
{
"id": 5,
"pid": 4,
"name": "裤子",
"child": []
}
]
}
]
},
{
"id": 2,
"pid": 0,
"name": "电子",
"child": [
{
"id": 6,
"pid": 2,
"name": "电脑",
"child": [
{
"id": 7,
"pid": 6,
"name": "笔记本电脑",
"child": []
}
]
},
{
"id": 8,
"pid": 2,
"name": "手机",
"child": []
}
]
},
{
"id": 3,
"pid": 0,
"name": "食品",
"child": []
}
]
相关文章:
PHP无限级分类(二)