递归-实现省市区三级联动


public static function linkage()
{
//由于数据量太大,只循环了pid=1的数据 (查询省市区的id,区域名称,父级id)
$data = Address::whereIn('type',[2,3,4])->get(['id','name','pid'])->toArray();
return self::getTree($data);
}
//递归
public static function getTree($data,$pid =1)
{
$list = [];
foreach ($data as $value)
{
//第一次遍历,找到父节点为1的
if ($value['pid'] == $pid){
//开始递归,查找父id为该节点id的节点
if (!empty(self::getTree($data, $value['id']))){
$value['childList'] = self::getTree($data, $value['id']);
}
$list[] = $value;
}
}
return $list;
 
posted @ 2021-06-30 17:09  西柚柠檬  阅读(909)  评论(0编辑  收藏  举报