[英]How i can print single element of object array in PHP?
我找到了使用Google API将地址转换为GPS经度/纬度的类。
我可以打印所有数组: print_r($geo->adress(my address)
。
它会显示
Array
(
[0] => stdClass Object
(
[location] => stdClass Object
(
[lat] => 53.1243946
[lng] => 18.001958
)
[city] => Bydgoszcz
[street] => MarszaĹka Focha
[number] => 4
[code] => 85-070
)
)
但是我无法打印单个元素。 我需要在变量中添加位置-> lat / lng,但是我无法将对象转换为字符串。 我怎样才能做到这一点?
$lat = implode(",", $geo->adress('Focha 4, Bydgoszcz'); // doesn't work at all.
<?php
echo "<pre>";
$geo = new GeoGoogle;
print_r($geo->adress('Focha 4, Bydgoszcz'));
echo"</pre>";
final class GeoGoogle {
// zwróć listę lokacji pasujących do podanego adresu
function adress($adress) {
return $this->parse(
$this->prepare(
'http://maps.googleapis.com/maps/api/geocode/json?address='
.urlencode($adress)
.'&sensor=false'
)
);
}
// zwróć listę lokacji pasujących do podanej długości i szerokości
function latlng($lat,$lng) {
return $this->parse(
$this->prepare(
'http://maps.googleapis.com/maps/api/geocode/json?latlng='
.$lat .','. $lng
.'&sensor=false'
)
);
}
/* pomocnicze */
private function prepare($uri) {
return json_decode( file_get_contents($uri) );
}
private function parse($data) {
if($data->status == 'OK') {
$results = array();
foreach($data->results as $res) { // przetwórz wyniki
$result = array(
'location' => null,
'city' => null,
'street' => null,
'number' => null,
'code' => null
);
// pobierz współrzędne
if(isset($res->geometry)) {
if(isset($res->geometry->location)) {
$result['location'] = $res->geometry->location;
}
}
// pobierz dane
foreach($res->address_components as $component) {
foreach($component->types as $type) {
switch($type) {
case 'street_number':
$result['number'] = $component->long_name;
break;
case 'route':
$result['street'] = $component->long_name;
break;
case 'postal_code':
$result['code'] = $component->long_name;
break;
case 'sublocality':
$result['city'] = $component->long_name;
break;
case 'administrative_area_level_3':
if(is_null($result['city'])) {
$result['city'] = $component->long_name;
}
break;
}
}
}
if(!is_null($result['city'])) {
$results[] = (object) $result;
}
}
return $results;
}
return array();
}
}
要从对象中获取“ lat”和“ lng”值,请尝试以下操作:
$lat = $object->location['lat'];
$lng = $object->location['lng'];
编辑:仔细查看您的数据,这可能会更有用:
$lat = $geo[0]->location['lat'];
$lng = $geo[0]->location['lng'];
编辑:关于注释中所述的错误, Cannot use object of type GeoGoogle as array
尝试这个:
$my_geo = $geo->adress(my address);
$lat = $my_geo[0]->location->lat;
$lng = $my_geo[0]->location->lng;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.