where('enabled', 1) ->order('sort asc, id asc') ->select(); foreach ($rows as $r) { $list[] = [ 'id' => (int)$r['id'], 'province' => (string)$r['province'], 'city' => (string)$r['city'], 'district' => (string)$r['district'], 'lat' => $r['lat'] !== null && $r['lat'] !== '' ? (float)$r['lat'] : null, 'lng' => $r['lng'] !== null && $r['lng'] !== '' ? (float)$r['lng'] : null, ]; } } catch (\Throwable $e) { // 数据库异常返回空 } self::$allCache = $list; return self::$allCache; } /** * 按区域 ID 查找单条省/市/区县记录 */ public static function findById($areaId) { $areaId = (int)$areaId; if ($areaId <= 0) { return null; } foreach (self::all() as $row) { if ((int)$row['id'] === $areaId) { return $row; } } return null; } /** * 按区县名称(及可选省/市)查找匹配记录 */ public static function findByName($district, $city = '', $province = '') { $district = trim((string)$district); $city = trim((string)$city); $province = trim((string)$province); if ($district === '') { return null; } foreach (self::all() as $row) { if ($row['district'] === $district) { if ($city !== '' && $row['city'] !== $city) { continue; } if ($province !== '' && $row['province'] !== $province) { continue; } return $row; } } return null; } /** * 清内存缓存 */ public static function invalidate() { self::$allCache = null; } /** * 从 national_areas.json 导入全国默认数据到 fa_fc_area * * 操作:先 TRUNCATE 清空现有覆盖层,再把 json 全量 INSERT 进去,全部 enabled=1。 * 相当于把"覆盖层"重置为全国默认状态。 * * @return int 导入条数 */ public static function importFromJson() { $jsonFile = APP_PATH . 'extra' . DS . 'national_areas.json'; if (!is_file($jsonFile)) { throw new \RuntimeException('national_areas.json 不存在'); } $decoded = json_decode((string)file_get_contents($jsonFile), true); if (!is_array($decoded)) { throw new \RuntimeException('national_areas.json 解析失败'); } // 清空现有覆盖层 Db::execute('TRUNCATE TABLE `' . Db::getConfig('prefix') . 'fc_area`'); // 按 省→市→区县 自然排序后再入库,保证 id 自增顺序就是行政区顺序 usort($decoded, function ($a, $b) { $cmp = strcmp((string)$a['province'], (string)$b['province']); if ($cmp !== 0) return $cmp; $cmp = strcmp((string)$a['city'], (string)$b['city']); if ($cmp !== 0) return $cmp; return strcmp((string)$a['district'], (string)$b['district']); }); $now = time(); $chunk = []; $chunkSize = 200; $sort = 0; foreach ($decoded as $item) { $sort++; $chunk[] = [ 'province' => (string)$item['province'], 'city' => (string)$item['city'], 'district' => (string)$item['district'], 'lat' => isset($item['lat']) && $item['lat'] !== null ? (float)$item['lat'] : null, 'lng' => isset($item['lng']) && $item['lng'] !== null ? (float)$item['lng'] : null, 'sort' => $sort, 'enabled' => 1, 'createtime' => $now, 'updatetime' => $now, ]; if (count($chunk) >= $chunkSize) { Db::name('fc_area')->insertAll($chunk); $chunk = []; } } if (!empty($chunk)) { Db::name('fc_area')->insertAll($chunk); } self::invalidate(); return count($decoded); } }