class Totree{
public function school_totree(){
$list=[
['id'=>1,'name'=>'学校','pid'=>0],
['id'=>2,'name'=>'一年级','pid'=>1],
['id'=>3,'name'=>'1班','pid'=>5],
['id'=>4,'name'=>'2班','pid'=>2],
['id'=>5,'name'=>'二年级','pid'=>1],
['id'=>6,'name'=>'3班','pid'=>5],
['id'=>7,'name'=>'4班','pid'=>5],
['id'=>8,'name'=>'4班','pid'=>2],
];
$res=$this->totree($list,$pid=0,$level=0);
echo '<pre>';
var_dump($res);
}
/**
* @description: 转成树形数据
* @param {*} $list 初始数据
* @param {*} $pid 父id
* @param {*} $level 层级
* @param {*} $pid_name pid字段名称 默认pid
* @param {*} $id_name 主键id 名称
* @return {*}
*/
public function totree($list,$pid=0,$level=0,$pid_name='pid',$id_name='id')
{
$arr=[];
$level++;
foreach($list as $k => $v){
if($pid==$v[$pid_name]){
$v['level']=$level;
$v['next']=$this->totree($list,$v[$id_name],$level,$pid_name,$id_name);
$arr[]=$v;
}
}
return $arr;
}
}
/**
* @description: 转成树形显示-
* @param {*} $result 结果
* @param {*} $list 初始数据
* @param {*} $pid 父id
* @param {*} $level 层级
* @param {*} $pid_name pid字段名称 默认pid
* @param {*} $id_name 主键id 名称
* @return {*}
*/
public function totreestr($list,$pid=0,$level=0,$pid_name='pid',$id_name='id')
{
$arr=[];
$level++;
foreach($list as $k => $v){
if($pid==$v[$pid_name]){
// $v['level']=$level;
$name_str='';
if($level>1){
for($i=0;$i<$level-1;$i++){
$name_str=$name_str.'▬';
}
}
$v['name']=$name_str.$v['name'];
$arr[]=$v;
$next=$this->totreestr($list,$v[$id_name],$level,$pid_name,$id_name);
if(!empty($next)){
foreach($next as $kk => $vv){
$arr[]=$vv;
}
}
}
}
return $arr;
}