PHP读取非嵌套JSON文件,根据short_name获取国家边界坐标
问题解决:根据short_name从JSON提取国家边界坐标
先修正JSON文件格式
你提供的JSON内容是两个独立对象直接拼接,并非合法的JSON数组,json_decode会解析失败。需要将内容用[]包裹,修正后的JSON如下:
[ {"long_name":"Ukraine","short_name":"ukr","center_lat":"48.379433","center_lng":"31.16558","sw_lat":"44.2924","sw_lng":"22.137159","ne_lat":"52.3793713","ne_lng":"40.2204802"}, {"long_name":"Zimbabwe","short_name":"zwe","center_lat":"-19.015438","center_lng":"29.154857","sw_lat":"-22.4219117","sw_lng":"25.237368","ne_lat":"-15.6093188","ne_lng":"33.068236"} ]
PHP实现逻辑
已获取目标short_name($area)并读取JSON文件后,按以下步骤提取坐标:
- 让JSON解析为关联数组(
json_decode第二个参数传true,方便取值操作) - 遍历数组,匹配
short_name与$area - 匹配成功后提取四个坐标,同时转为数值类型(原JSON中坐标是字符串格式)
- 处理未匹配到目标条目的情况
完整代码示例:
// 已获取的目标short_name $area = cot_import('area', 'G', 'ALP'); // 读取并解析JSON文件 $str = file_get_contents('/countries.json'); // 第二个参数true转为关联数组 $countries = json_decode($str, true); // 初始化坐标变量 $sw_lat = $ne_lat = $sw_lng = $ne_lng = null; // 遍历匹配目标条目 if (!empty($countries)) { foreach ($countries as $country) { if ($country['short_name'] === $area) { // 提取坐标并转为数值类型 $sw_lat = (float)$country['sw_lat']; $ne_lat = (float)$country['ne_lat']; $sw_lng = (float)$country['sw_lng']; $ne_lng = (float)$country['ne_lng']; // 找到匹配后跳出循环,无需继续遍历 break; } } } // 后续业务处理示例 if ($sw_lat !== null) { echo "sw_lat: {$sw_lat}, ne_lat: {$ne_lat}, sw_lng: {$sw_lng}, ne_lng: {$ne_lng}"; } else { echo "未找到对应国家的边界坐标"; }
关键提示
- 必须修正JSON格式为数组,否则
json_decode会返回null,无法进行后续操作 - 把字符串坐标转为数值类型,方便后续计算或业务使用
- 匹配到目标后立即终止循环,提升执行效率
内容的提问来源于stack exchange,提问作者Andrew Zheludkov
相关产品推荐
相关产品推荐

