php常用函数:列表转树结构
function list_to_tree($list, $root = 0,$pk = 'id', $pid = 'pid', $child = '_child') {
// 创建Tree
$tree = array();
if (is_array($list)){
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] = &$list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId=0;
if(isset($data[$pid])){
$parentId =$data[$pid] ;
}
if ($root == $parentId) {
$tree[] = &$list[$key];
} else {
if (isset($refer[$parentId])) {
$parent = &$refer[$parentId];
$parent[$child][] = &$list[$key];
}
}
}
}
return $tree;
}
树转列表
function tree_to_list($tree, $level = 0,$pk = 'id', $pid = 'pid', $child = '_child'){
$list = array();
if (is_array($tree)){
foreach($tree as $val) {
$val['level']=$level;
$child=$val['_child'];
if(isset($child)){
if (is_array($child)){
unset($val['_child']);
$list=$val;
$list = array_merge($list, tree_to_list($child,$level+1));
}
}else{
$list=$val;
}
}
return $list;
}
}