如何从经纬度逆地理编码API返回结果中提取州名与州代码?
解决PHP中从逆地理编码API提取州名与州代码的问题
问题描述
我购买了一款支持经纬度逆地理编码的API,原本可从中提取州名与州缩写,但现在出现PHP报错。当前使用代码如下:
$json = @file_get_contents($url); $result = array_values(json_decode($json, true)); print_r($result);
调用后返回数组结构如下,请问如何设置变量分别获取州名(State Name)和州代码(State Code)?
Array ( [0] => FeatureCollection [1] => Array ( [0] => Array ( [type] => Feature [properties] => Array ( [datasource] => Array ( [sourcename] => openstreetmap [attribution] => © OpenStreetMap contributors [license] => Open Database License [url] => https://www.openstreetmap.org/copyright ) [country] => United States [country_code] => us [state] => North Carolina [county] => Cumberland County [city] => Hope Mills [hamlet] => Timberlake [postcode] => 28348 [street] => Labonte Drive [housenumber] => 5941 [lon] => -78.976173283181 [lat] => 34.974986403843 [state_code] => NC [distance] => 8.514796509686 [result_type] => building [formatted] => 5941 Labonte Drive, Hope Mills, NC 28348, United States of America [address_line1] => 5941 Labonte Drive [address_line2] => Hope Mills, NC 28348, United States of America [timezone] => Array ( [name] => America/New_York [offset_STD] => -05:00 [offset_STD_seconds] => -18000 [offset_DST] => -04:00 [offset_DST_seconds] => -14400 [abbreviation_STD] => EST [abbreviation_DST] => EDT ) [rank] => Array ( [importance] => -1.15 [popularity] => 1.8893922812046 ) [place_id] => 51809f819f79be53c0596246bf5acc7c4140f00102f901f3abfb0000000000c00203 ) [geometry] => Array ( [type] => Point [coordinates] => Array ( [0] => -78.976173283181 [1] => 34.974986403843 ) ) [bbox] => Array ( [0] => -78.976223283181 [1] => 34.974936403843 [2] => -78.976123283181 [3] => 34.975036403843 ) ) ) )
解决方案
第一步:排查报错原因
先去掉 @ 符号屏蔽错误,查看具体报错信息,确定是API请求失败还是JSON解码异常:
$json = file_get_contents($url); if (!$json) { die("API请求失败"); } $result = json_decode($json, true); if (json_last_error() !== JSON_ERROR_NONE) { die("JSON解码失败:" . json_last_error_msg()); }
第二步:提取州名与州代码
根据返回的数组结构,通过层级索引直接访问目标字段,同时添加容错处理避免键不存在时抛出警告:
// 基于当前array_values转换后的数组结构提取 $stateName = $result[1][0]['properties']['state'] ?? '未知州名'; $stateCode = $result[1][0]['properties']['state_code'] ?? '未知州代码'; // 更推荐的方式:不使用array_values,保留原API返回的键名(可读性更强、容错性更高) // $result = json_decode($json, true); // 去掉array_values // $features = $result['features'] ?? []; // if (!empty($features)) { // $properties = $features[0]['properties'] ?? []; // $stateName = $properties['state'] ?? '未知州名'; // $stateCode = $properties['state_code'] ?? '未知州代码'; // } // 输出结果 echo "州名:{$stateName}\n"; echo "州代码:{$stateCode}";
关键说明
- 使用
??空合并运算符,确保当目标字段不存在时返回默认值,避免PHP警告; - 优先保留原API返回的键名(如
features),而非用array_values转为索引数组,这样代码更易维护,适配API结构的细微变动。
内容的提问来源于stack exchange,提问作者user3384413
相关产品推荐
相关产品推荐

