首先推荐一个开源项目:点此查看
优点:开箱即用
缺点:没法及时更新,例如:地名更改无法及时更新
想要及时更新,可以基于高德地图的行政区域查询来做一个:
public function init(){
$url = 'http://restapi.amap.com/v3/config/district?key=您的key&keywords=中国&subdistrict=3&extensions=base';
$stream_opts = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
$res = file_get_contents($url, false, stream_context_create($stream_opts));
$resArr = json_decode($res, true);
$data = $resArr['districts'][0]['districts'];
$this->createDistrict($data, 0);
}
private function createDistrict($arr=[],$parentid=0){
//按区域编码排序
$key = array_column($arr, 'adcode');
array_multisort($key, SORT_ASC, $arr);
foreach ($arr as $k => $v) {
$pid = Db::name('district')->insertGetId([
'name' => $v['name'],
'center' => $v['center'],
'citycode' => $v['citycode'],
'adcode' => $v['adcode'],
'pid' => $parentid,
]);
if (array_key_exists('districts', $v) && !empty($v['districts'])) {
$this->createDistrict($v['districts'], $pid);
}
}
}