十行代码搞定无限极分类

function tree($data,$pid=0,$level=0){
   static $tree=[];
    foreach ($data as $key=>$vo){
        if ($vo['pid']==$pid){
            $vo['level']=str_repeat('-', $level);;
            $tree[]=$vo;
            tree($data,$vo['id'],$level+1);
     }

    }
    return $tree;
}



缺点:$tree是静态,只能用一次
//无线级分类
function tree(&$data,$pid=0,$level=0){
    $tree=[];
    foreach ($data as $key=>$vo){
        if ($vo['pid']==$pid){
            $vo['level']=str_repeat('--', $level);;
            $tree[]=$vo;
            $tree=array_merge($tree,tree($data,$vo['id'],$level+1));
     }

    }
    return $tree;
}


 
  
 
  
 
 

你可能感兴趣的:(PHP)