利用高德API获取最新的省市区数据

直接上代码,只是保存数据,所以实现功能即可,代码有点乱

 1 $key = 'xxxxx';//自己去高德申请即可
 2 $url = 'https://restapi.amap.com/v3/config/district?subdistrict=3&key='.$key;
 3 $res = file_get_contents($url);
 4 
 5 $res = json_decode($res,true);//转换数组
 6 
 7 $str = 'insert into fa_area values';//插入数据库
 8 //        $data = [];
 9 foreach ($res['districts'] as $v) {
10     //循环一次
11     $str .= "(null,".$v['adcode'].",'".$v['name']."',0,0), ";
12     foreach ($v['districts'] as $vv) {
13         //循环34次
14         $str .= "(null,".$vv['adcode'].",'".$vv['name']."',1,".$v['adcode']."), ";
15         foreach ($vv['districts'] as $vvv) {
16 
17             $str .= "(null,".$vvv['adcode'].",'".$vvv['name']."',2,".$vv['adcode']."), ";
18             //循环市
19 //                    $temp_3[$vvv['adcode']] = [];
20 //                    $temp_4 = [];
21             foreach ($vvv['districts'] as $kkkk=>$vvvv) {
22                 //循环区县
23 //                        $temp_4[$vvvv['adcode']] = $vvvv['name'];
24                 $code = $vvvv['adcode'];
25                 $str .= "(null,$code,'".$vvvv['name']."',3,".$vvv['adcode']."), ";
26             }
27 //                    ksort($temp_4);
28 //                    $temp_3[$vvv['adcode']][] = $temp_4;
29         }
30 //                ksort($temp_3);
31 //                $data[] = $temp_3;
32     }
33 }
34 $str = rtrim($str, ', ');//删除最后一个空格
35 //        echo $str;
36 Db::name('area')->query($str);
37 die;
38 //        file_put_contents('area.txt',json_encode($data));//写入文件

这是fa_area表结构

1 CREATE TABLE `fa_area` (
2   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
3   `code` int(10) NOT NULL,
4   `name` varchar(50) NOT NULL,
5   `level` tinyint(1) unsigned NOT NULL COMMENT '层级0-3',
6   `pid` int(10) unsigned DEFAULT NULL COMMENT '上级code',
7   PRIMARY KEY (`id`)
8 ) ENGINE=InnoDB AUTO_INCREMENT=3725 DEFAULT CHARSET=utf8mb4 COMMENT='省市区';

这里需要注意的地方,就是有些市下面直接就是乡镇了,比如河南省济源市,所以需要注意这种数据的处理,切勿直接将adcode当做id,否则会重复

posted @ 2020-05-26 16:45  落日长烟  阅读(1795)  评论(0编辑  收藏  举报