PHP实现无限级分类
public function generateTree($items){ $tree = array(); foreach($items as $item){ if(isset($items[$item['pid']])){ $items[$item['pid']]['son'][] = &$items[$item['id']]; }else{ $tree[] = &$items[$item['id']]; } } return $tree; } public function fenleitest(){ $depart_list = [ 1 => ['id' => 1, 'grp_name' => '技术部', 'pid' => 0], 2 => ['id' => 2, 'grp_name' => '业务中台', 'pid' => 1], 3 => ['id' => 3, 'grp_name' => '业务前台', 'pid' => 1], 4 => ['id' => 4, 'grp_name' => '业务后台', 'pid' => 1], 5 => ['id' => 5, 'grp_name' => '客服组', 'pid' => 2], 6 => ['id' => 6, 'grp_name' => '管理系统组', 'pid' => 2], 7 => ['id' => 7, 'grp_name' => '支付组', 'pid' => 2], 8 => ['id' => 8, 'grp_name' => '用户组', 'pid' => 4], 9 => ['id' => 9, 'grp_name' => '司机组', 'pid' => 4], 10 => ['id' => 10, 'grp_name' => 'ios组', 'pid' => 3], 11 => ['id' => 11, 'grp_name' => 'android组', 'pid' => 3], ]; $depart_data = $this->generateTree($depart_list); print_r($depart_data); exit(); }
Array ( [0] => Array ( [id] => 1 [grp_name] => 技术部 [pid] => 0 [son] => Array ( [0] => Array ( [id] => 2 [grp_name] => 业务中台 [pid] => 1 [son] => Array ( [0] => Array ( [id] => 5 [grp_name] => 客服组 [pid] => 2 ) [1] => Array ( [id] => 6 [grp_name] => 管理系统组 [pid] => 2 ) [2] => Array ( [id] => 7 [grp_name] => 支付组 [pid] => 2 ) ) ) [1] => Array ( [id] => 3 [grp_name] => 业务前台 [pid] => 1 [son] => Array ( [0] => Array ( [id] => 10 [grp_name] => ios组 [pid] => 3 ) [1] => Array ( [id] => 11 [grp_name] => android组 [pid] => 3 ) ) ) [2] => Array ( [id] => 4 [grp_name] => 业务后台 [pid] => 1 [son] => Array ( [0] => Array ( [id] => 8 [grp_name] => 用户组 [pid] => 4 ) [1] => Array ( [id] => 9 [grp_name] => 司机组 [pid] => 4 ) ) ) ) ) )
ps:数组key 必须跟 id一致 (还有必须大于)
我封装了下算法(id不变哦 让id改成跟key一样)
public function keyequalid($lists)
{
$list = array();
foreach ($lists as $k => $v) {
$j=$v[‘id’];
$list[$j] = $v;
}
return $list;
}
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/19011.html