我正在尝试使用这些网址返回的JSON:
http://maps.googleapis.com/maps/api/geocode/json?latlng=12.0,12.0&sensor=false
这就是我所做的:
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=12.0,12.0&sensor=false';
$data = json_decode( file_get_contents( $url ), true );
print_r( $data );
这是输出:
Array (
[0] => Array (
[address_components] => Array (
[0] => Array (
[long_name] => Chungul Jabarari-Dabalam-Jajere Road
[short_name] => Chungul Jabarari-Dabalam-Jajere Road
[types] => Array ( [0] => route ) )
[1] => Array (
[long_name] => Yobe [short_name] => Yobe
[types] => Array (
[0] => administrative_area_level_1
[1] => political ) )
[2] => Array (
[long_name] => Nigeria
[short_name] => NG
[types] => Array (
[0] => country
[1] => political ) )
....
正如您所看到的,address_components
位于[0]
下,这使得在数组数量未知时难以使用此结果集。
假设我想获得美国郡的administrative_area_level_2
,但尼日利亚显然不存在?
然后我想说我想访问美国['results'][0]['address_components'][6]
但在尼日利亚['results'][0]['address_components'][3]
当子数组的数量不可靠时,我要求的是访问此数组中每个数据元素的有效方法。
(或者更好地解码JSON以生成一个没有这些无用索引的数组,并且只是一个纯粹的关联数组。)
答案 0 :(得分:1)
如果存在administrative_area_level_2
,则返回名称,如果不存在则返回“N / A”。请注意,这可能是有些低效的(循环和检查可能不存在的东西),但它可能会像这样的东西一样好。
function getAdminAreaLevel2($data)
{
foreach($data['results'][0]['address_components'] as $component)
{
if(in_array("administrative_area_level_2", $component['types']))
{
return $component['long_name'];
}
}
return "N/A";
}
echo getAdminAreaLevel2($firstData);
echo "\r\n";
echo getAdminAreaLevel2($secondData);
答案 1 :(得分:-1)
$data = json_decode($url,true);
$address_component = false;
foreach($data['results'] as $value) {
if(isset($value['address_components'])) {
$address_component = $value['address_components'];
break;
}
}
if($address_component) {
echo $address_component[6]['long_name'];
}