php无限极分类
2018-12-29 本文已影响0人
Mr_Laoyu
递归--无限极分类
/*
*p1 数据源
*p2 类型$type=1返回一个二维数组,$type=2返回子孙树
*p3 初始父id
*p4 分类等级
*/
function unlimitTree(array $data,$type=1,$pid=0,$level=1)
{
if($type == 1){
static $tree = [];
}else{
$tree = [];
}
foreach($data as $key => $value) {
if($value['pid'] == $pid) {
if($type == 1){
$value['level'] = $level;
$tree[] = $value;
unlimitTree($data,$type,$value['id'],$level+1);
}else{
$value['level'] = $level;
$value['children'] = unlimitTree($data,$type,$value['id'],$level+1);
$tree[$value['id']] = $value;
}
}
}
return $tree;
}
//5行代码非递归实现无限极分类树
function genTree5($items) {
foreach ($items as $item){
$items[$item['pid']]['children'][$item['id']] = &$items[$item['id']];
}
return $items[0]['children']) ?? [];
}
递归--子孙树转二维数组 可以配合Nestable使用
$json = '[{"id":1,"children":[{"id":2,"children":[{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]}]},{"id":3},{"id":11},{"id":12}]';
$arr = json_decode($json,true);
$rows = tree_to_row($arr);
function tree_to_row(array $tree,$pid = 0,$childname='children'){
static $rows = [];
//简单排序
$sort = count($tree);
foreach($tree as $val){
$rows[] = ['id'=>$val['id'],'pid'=>$pid,'sort'=>$sort];
$sort--;
if(isset($val[$childname])){
tree_to_row($val[$childname],$val['id']);
}
}
return $rows;
}
递归--获取树所有叶子节点
$json = '[{"id":1,"children":[{"id":2,"children":[{"id":4,"children":[{"id":6},{"id":7}]},{"id":5,"children":[{"id":8},{"id":9}]},{"id":10}]}]},{"id":3},{"id":11},{"id":12}]';
$arr = json_decode($json,true);
$rows = all_child_node($arr);
function all_child_node(array $tree,$pre = 0){
static $rows = [];
foreach ($tree as $key=>$val){
$id = $val['id'];
$children = $val['children'] ?? null;
if($children){
$rows[$id] = all_child_node($children,'id');
exo($children,$id);
if($pre != 0){
$rows[$pre] = array_merge($rows[$pre]??[],$rows[$id]);
}
}else{
$rows[$id] = [];
}
}
return $rows;
}