/**
* Notes:省市县三级联动
* Created by depressiom
* Date: 2022年4月14日
*/
public function getCityData(){
//获取一级
$cityList = M('area')->where(['type'=>0])->select(); // 根据type 取一级
$data = array();
if(count($cityList)>0){
foreach ($cityList as $v) {
$data[$v['id']] = array(
"id" => $v['id'],
"value" => $v['area_code'],
"label" => $v['name'],
"children" => array()
);
//获取二级
$cityTow = M('area')->where(['type' => 1,'parent_code'=>$v['id']])->select(); // 数据库通过关联的 一级id为 二级的父code type为1 表示市区
if(count($cityTow)>0) {
foreach ($cityTow as $l) {
$data[$v['id']]['children'][$l['id']] = array(
"id" => $l['id'],
"value" => $l['area_code'], // 这里因为第一次取得是$v的值 所以出现二级与一级name一样
"label" => $l['name'],
"children" => array()
);
//获取三级
$cityThree = M('area')->where(['type' => 2, 'parent_code' => $l['id']])->select(); // 三级同理
if(count($cityTow)>0) {
foreach ($cityThree as $t) {
$data[$v['id']]['children'][$l['id']]['children'][] = array(
"id" => $t['id'],
"value" => $t['area_code'],
"label" => $t['name'],
);
}
}else{
$msg = array(
"status" => -1,
"msg" => "获取县数据失败!",
"result" => null
);
$this->ajaxReturn($msg);
exit ();
}
}
}else{
$msg = array(
"status" => -1,
"msg" => "获取市数据失败!", //.json_encode($cityTow,true) 数据不正常是前端展示查看结果
"result" => null
);
$this->ajaxReturn($msg);
exit ();
}
}
}else{
$msg = array(
"status" => -1,
"msg" => "获取省数据失败!",
"result" => null
);
$this->ajaxReturn($msg);
exit ();
}
if (count($data)<=0) {
$msg = array(
"status" => -1,
"msg" => "数据出错",
"result" => null
);
$this->ajaxReturn($msg);
exit ();
}
//格式化数据
$res = array();
foreach ($data as $val) {
$item = array();
foreach ($val['children'] as $v) {
$item[] = $v;
}
$res[] = array(
'id' => $val['id'],
"value" => $val['value'], // 这里是格式化数据,因为我第一层格式已经将$data里面的字段名字改变 所以用已改变的值,就是因为这里导致找了半小时
"label" => $val['label'],
'children' => $item
);
}
$msg = array(
"status" => 1,
"msg" => "数据获取成功",
"result" => $res,
"data"=>$data,
);
$this->ajaxReturn($msg);
}
感谢大佬的分享 原作者地址
本文来自博客园,作者:depressiom,转载请注明原文链接:https://www.cnblogs.com/depressiom/p/16144070.html