quanwei
2025-12-12 b8961f178740f99ce54cfcbfd88235eaf8b79872
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<?php
 
namespace app\common\model\settings;
 
use think\facade\Cache;
use app\common\library\helper;
use app\common\model\BaseModel;
/**
 * 地区模型
 */
class Region extends BaseModel
{
    protected $name = 'region';
    protected $pk = 'id';
    protected $createTime = false;
    protected $updateTime = false;
 
    /**
     * 类型自动转换
     * @var array
     */
    protected $type = [
        'id' => 'integer',
        'pid' => 'integer',
        'level' => 'integer',
    ];
 
    // 当前数据版本号
    private static $version = '1.2.3';
 
    // 县级市别名 (兼容微信端命名)
    private static $county = [
        '省直辖县级行政区划',
        '自治区直辖县级行政区划',
    ];
 
    /**
     * 根据id获取地区名称
     */
    public static function detail($id)
    {
        return (new static())->find($id);
    }
 
    /**
     * 根据id获取地区名称
     */
    public static function getNameById($id)
    {
        return $id > 0 ? self::getCacheAll()[$id]['name'] : '其他';
    }
 
    /**
     * 根据名称获取地区id
     */
    public static function getIdByName($name, $level = 0, $pid = 0)
    {
        // 兼容:微信端"省直辖县级行政区划"
        if (in_array($name, static::$county)) {
            $name = '直辖县级';
        }
        $data = self::getCacheAll();
        foreach ($data as $item) {
            if ($item['name'] == $name && $item['level'] == $level && $item['pid'] == $pid)
                return $item['id'];
        }
        return 0;
    }
    /**
     * 根据名称获取地区id
     */
    public static function getIdByCityName($name, $level = 0)
    {
        // 兼容:微信端"省直辖县级行政区划"
        if (in_array($name, static::$county)) {
            $name = '直辖县级';
        }
        $data = self::getCacheAll();
        foreach ($data as $item) {
            if ($item['name'] == $name && $item['level'] == $level)
                return $item['id'];
        }
        return 0;
    }
    /**
     * 获取所有地区(树状结构)
     */
    public static function getCacheTree()
    {
        return static::getCacheData('tree');
    }
 
    /**
     * 获取所有地区列表
     */
    public static function getCacheAll()
    {
        return static::getCacheData('all');
    }
 
    /**
     * 获取所有地区的总数
     */
    public static function getCacheCounts()
    {
        return static::getCacheData('counts');
    }
 
    /**
     * 获取缓存中的数据(存入静态变量)
     */
    private static function getCacheData($item = null)
    {
        static $cacheData = [];
        if (empty($cacheData)) {
            $static = new static;
            $cacheData = $static->regionCache();
        }
        if (is_null($item)) {
            return $cacheData;
        }
        return $cacheData[$item];
    }
 
    /**
     * 获取地区缓存
     */
    private function regionCache()
    {
        // 缓存的数据
        $complete = Cache::get('region');
        // 如果存在缓存则返回缓存的数据,否则从数据库中查询
        // 条件1: 获取缓存数据
        // 条件2: 数据版本号要与当前一致
        if (
            !empty($complete)
            && isset($complete['version'])
            && $complete['version'] == self::$version
        ) {
            return $complete;
        }
        // 所有地区
        $allList = $tempList = $this->getAllList();
        // 已完成的数据
        $complete = [
            'all' => $allList,
            'tree' => $this->getTreeList($allList),
            'counts' => $this->getCount($allList),
            'version' => self::$version,
        ];
        // 写入缓存
        Cache::tag('cache')->set('region', $complete);
        return $complete;
    }
 
    private static function getCount($allList)
    {
        $counts = [
            'total' => count($allList),
            'province' => 0,
            'city' => 0,
            'region' => 0,
        ];
        $level = [1 => 'province', 2 => 'city', 3 => 'region'];
        foreach ($allList as $item) {
            $counts[$level[$item['level']]]++;
        }
        return $counts;
    }
 
    /**
     * 格式化为树状格式
     */
    private function getTreeList($allList)
    {
        $treeList = [];
        foreach ($allList as $pKey => $province) {
            if ($province['level'] == 1) {    // 省份
                $treeList[$province['id']] = $province;
                unset($allList[$pKey]);
                foreach ($allList as $cKey => $city) {
                    if ($city['level'] == 2 && $city['pid'] == $province['id']) {    // 城市
                        $treeList[$province['id']]['city'][$city['id']] = $city;
                        unset($allList[$cKey]);
                        foreach ($allList as $rKey => $region) {
                            if ($region['level'] == 3 && $region['pid'] == $city['id']) {    // 地区
                                $treeList[$province['id']]['city'][$city['id']]['region'][$region['id']] = $region;
                                unset($allList[$rKey]);
                            }
                        }
                    }
                }
            }
        }
        return $treeList;
    }
 
    /**
     * 从数据库中获取所有地区
     */
    private function getAllList()
    {
        $list = self::withoutGlobalScope()
            ->field('id, pid, name, level, first, pinyin')
            ->select()
            ->toArray();
        return helper::arrayColumn2Key($list, 'id');
    }
 
    /**
     * 地区组装供前端使用
     */
    public static function getRegionForApi(){
        $province_arr = [];
        $city_arr = [];
        $area_arr = [];
        $region = self::getCacheTree();
        foreach ($region as $province){
            $value = [
                'label' => $province['name'],
                'value' => $province['id']
            ];
            array_push($province_arr, $value);
 
            $city_arr_temp = [];
            $city_area_temp = [];
            if(!isset($province['city'])){
                continue;
            }
            foreach ($province['city'] as $city){
                $value = [
                    'label' => $city['name'],
                    'value' => $city['id']
                ];
                array_push($city_arr_temp, $value);
                $area_arr_temp = [];
                if(isset($city['region'])){
                    foreach ($city['region'] as $area) {
                        $value = [
                            'label' => $area['name'],
                            'value' => $area['id']
                        ];
                        array_push($area_arr_temp, $value);
                    }
                }
                array_push($city_area_temp, $area_arr_temp);
            }
            array_push($area_arr, $city_area_temp);
            array_push($city_arr, $city_arr_temp);
        }
        return [$province_arr, $city_arr, $area_arr];
    }
 
    /**
     * 根据fullcode行政编码获取地区名称
     */
    public static function getNameByFullCode($code)
    {
        $data = self::getCacheAll();
        foreach ($data as $item) {
            if ($item['code'] == $code)
                return $item['name'];
        }
        return NULL;
    }
 
    /**
     * 根据id获取父地区名称
     */
    public static function getParentNameById($id)
    {
        $data = self::getCacheAll();
        $pid = 0;
        foreach ($data as $item) {
            if ($item['id'] == $id) {
                $pid = $item['pid'];
                break;
            }
        }
        if ($pid) {
           return self::getNameById($pid); 
        }
        return NULL;
    }
}