[英]How do I get from JS array through JSON to a PHP array? (I'm at least halfway there)
[英]PHP: How do I get an attribute from a JSON array?
我有以下JSON数组:
<?php
$json = {
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "5721 N Northcott Ave, Chicago, IL 60631, USA",
"address_components": [ {
"long_name": "5721",
"short_name": "5721",
"types": [ "street_number" ]
}, {
"long_name": "Illinois",
"short_name": "IL",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "60631",
"short_name": "60631",
"types": [ "postal_code" ]
} ],
"geometry": {
"location": {
"lat": 41.9858860,
"lng": -87.7907460
},
"location_type": "ROOFTOP",
"viewport": {
"southwest": {
"lat": 41.9827384,
"lng": -87.7938936
},
"northeast": {
"lat": 41.9890336,
"lng": -87.7875984
}
}
}
} ]
};
?>
使用PHP,如何从上面的JSON数组中获取geometery->location->lat
& lng
值?
例如(伪代码):
<?php
$lat = $json['geometry']['location']['lat']; // 41.9858860
$lng = $json['geometry']['location']['lng']; // -87.7907460
?>
你使用json_decode
然后$var->results[0]->geometry->location->lat;
。
json_decode
产生以下结构:
object()[] 'status' => string 'OK' 'results' => array 0 => object()[] 'types' => array 0 => string 'street_address' 'formatted_address' => string '5721 N Northcott Ave, Chicago, IL 60631, USA' 'address_components' => array 0 => object()[] 'long_name' => string '5721' 'short_name' => string '5721' 'types' => array 0 => string 'street_number' 1 => object()[] 'long_name' => string 'Illinois' 'short_name' => string 'IL' 'types' => array 0 => string 'administrative_area_level_1' 1 => string 'political' 2 => object()[] 'long_name' => string '60631' 'short_name' => string '60631' 'types' => array 0 => string 'postal_code' 'geometry' => object()[] 'location' => object()[] 'lat' => float 41.985886 'lng' => float -87.790746 'location_type' => string 'ROOFTOP' 'viewport' => object()[] 'southwest' => object()[] 'lat' => float 41.9827384 'lng' => float -87.7938936 'northeast' => object()[] 'lat' => float 41.9890336 'lng' => float -87.7875984
你使用json_decode
。
例如:
$json_obj = json_decode($json);
echo $json_obj->results[0]->geometry->location->lat;
我们访问结果数组的第一个元素,然后浏览几何,位置和纬度属性。 您也可以使用关联数组,但默认为对象。
问候,
我建议阅读json_decode文档
<?php
$obj = json_decode($json);
$lat = $obj->results[0]->geometry->location->lat;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.