刚出来混的时候,对递归不是特别懂,后来多研究了会儿,这时候把之前的东西补上,汇成文档的形式记录下来。
//递归无限极分类
private function makeTree($list,$pk = 'id', $pid='pid',$name='child',$root=0)
{
$tree = array();
foreach ($list as $key=>$val){
if ($val[$pid] == $root){
unset($list[$key]);
if (!empty($list)){
$tmpChild = self::makeTree($list,$pk,$pid,$name,$val[$pk]);
if (!empty($tmpChild)){
$val[$name] = $tmpChild;
}
}
$tree[] = $val;
}
}
return $tree;
}
如果调用的话,可以像下面的
$province = DB::select("select 0 as pid,Code as id,Name from fl_province order by code");
$city = DB::table('fl_city')
->select('ProAdCode as pid','CityAdCode as id','Name')
->get()->toArray();
$county = DB::table('fl_county')
->select('AdminCode as id','CityAdCode as pid','Name')
->get()->toArray();
$data = array_merge($province,$city,$county);
foreach ($data as $v)
{
$list[] = [
'value' => $v->id,
'pid' => $v->pid,
'label' => $v->Name,
];
}
$list = $this->makeTree($list,'value','pid','children',0);
return $list;
这个是用的省市县三级来测试的,在有些菜单想要是下面图片的树结构的时候,就可以使用此方法来做。
结果.png
网友评论