我正在尝试重新格式化地址。
所以我想使用Google地理编码API。 这是一个输出
{
"results" : [
{
"address_components" : [
{
"long_name" : "301",
"short_name" : "301",
"types" : [ "subpremise" ]
},
{
"long_name" : "880",
"short_name" : "880",
"types" : [ "street_number" ]
},
{
"long_name" : "N Street",
"short_name" : "N St",
"types" : [ "route" ]
},
{
"long_name" : "South Addition",
"short_name" : "South Addition",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Anchorage",
"short_name" : "Anchorage",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Anchorage",
"short_name" : "Anchorage",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Alaska",
"short_name" : "AK",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "99501",
"short_name" : "99501",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "880 N Street #301, Anchorage, AK 99501, USA",
"geometry" : {
"location" : {
"lat" : 61.21391800000001,
"lng" : -149.908357
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 61.21526698029151,
"lng" : -149.9070080197085
},
"southwest" : {
"lat" : 61.2125690197085,
"lng" : -149.9097059802915
}
}
},
"partial_match" : true,
"types" : [ "subpremise" ]
}
],
"status" : "OK"
}
如何获取街道号码,街道地址,套件#(如果有),城市,州,邮政编码。
令我困惑的部分是address_component具有不同的组件。我怎么知道每个人代表什么?
我以为我可以做这样的事情来得到我需要的东西
<?php
$obj = json_decode($json, true);
$c = $obj['results'][0]['address_components'];
echo '</pre>';
echo 'BUILDING NAME: ' . $c[1]['long_name'] . "<br>\n";
echo 'BUILDING NUMBER: ' . $c[2]['long_name'] . "<br>\n";
echo 'STREET NAME: ' . $c[3]['long_name'] . "<br>\n";
echo 'CITY: ' . $c[5]['long_name'] . "<br>\n";
echo 'COUNTY: ' . $c[6]['long_name'] . "<br>\n";
echo 'STATE: ' . $c[7]['short_name'] . "<br>\n";
echo 'COUNTRY: ' . $c[8]['short_name'] . "<br>\n";
echo 'POSTAL CODE: ' . $c[9]['short_name'] . "<br>\n";
?>
但这对所有地址都不起作用。使用上面的地址是我的输出。正如你所知,标签与数据不符。
BUILDING NAME: 880
BUILDING NUMBER: N Street
STREET NAME: South Addition
CITY: Anchorage
COUNTY: Alaska
STATE: US
COUNTRY: 99501
我怎样才能让每次所需的结果都正确? 我的假设是,我会以某种方式检查类型值,但我不确定如何以及我需要查看的规则是什么。
答案 0 :(得分:0)
这是一个快速的功能,我把它放在一起,这里是fiddle:
function getAddress($elements){
$addr = [];
foreach($elements as $e){
if(isset($e['types']) && in_array("street_number",$e['types'])) $addr['street_number'] = $e['long_name'];
if(isset($e['types']) && in_array("street_number",$e['types'])) $addr['route'] = $e['long_name'];
if(isset($e['types']) && in_array("administrative_area_level_2",$e['types'])) $addr['city'] = $e['long_name'];
}
return $addr;
}
虽然我没有为你做所有的工作。这只是为了给你一个如何做的例子。您必须对其进行编辑以获取其余信息。
样本用法:
$obj = json_decode($json, true);
$c = $obj['results'][0]['address_components'];
$address_parts = getAddress($c);
输出一个简单的数组:
array(3) { ["street_number"]=> string(3) "880" ["route"]=> string(3) "880" ["city"]=> string(9) "Anchorage" }