/**
* 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
分类:
工作踩坑记录
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)