使用 Laravel 从数组中获取 JSON 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31234459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a JSON value from an array using Laravel
提问by Jigs Virani
I am trying to get the latitude and longitude values from a JSON array - $response
, returned from Google, from their Geocoding services.
我试图从 JSON 数组中获取纬度和经度值 -$response
从谷歌返回,从他们的地理编码服务。
The JSON array is returned as such (random address):
JSON 数组按原样返回(随机地址):
{
"results":[
{
"address_components":[
{
"long_name":"57",
"short_name":"57",
"types":[
"street_number"
]
},
{
"long_name":"Polo Gardens",
"short_name":"Polo Gardens",
"types":[
"route"
]
},
{
"long_name":"Bucksburn",
"short_name":"Bucksburn",
"types":[
"sublocality_level_1",
"sublocality",
"political"
]
},
{
"long_name":"Aberdeen",
"short_name":"Aberdeen",
"types":[
"locality",
"political"
]
},
{
"long_name":"Aberdeen",
"short_name":"Aberdeen",
"types":[
"postal_town"
]
},
{
"long_name":"Aberdeen City",
"short_name":"Aberdeen City",
"types":[
"administrative_area_level_2",
"political"
]
},
{
"long_name":"United Kingdom",
"short_name":"GB",
"types":[
"country",
"political"
]
},
{
"long_name":"AB21 9JU",
"short_name":"AB21 9JU",
"types":[
"postal_code"
]
}
],
"formatted_address":"57 Polo Gardens, Aberdeen, Aberdeen City AB21 9JU, UK",
"geometry":{
"location":{
"lat":57.1912463,
"lng":-2.1790257
},
"location_type":"ROOFTOP",
"viewport":{
"northeast":{
"lat":57.19259528029149,
"lng":-2.177676719708498
},
"southwest":{
"lat":57.18989731970849,
"lng":-2.180374680291502
}
}
},
"partial_match":true,
"place_id":"ChIJLTex1jQShEgR5UJ2DNc6N9s",
"types":[
"street_address"
]
}
],
"status":"OK"
}
I have tried the following:
我尝试了以下方法:
json_decode($response->results->geometry->location->lat)
But it returns 'trying to access the property of a non-object'.
但它返回“试图访问非对象的属性”。
Any help would be hugely appreciated.
任何帮助将不胜感激。
回答by splash58
var_dump(json_decode($response)->results[0]->geometry->location->lat);
回答by Jigs Virani
Either pass true as the second parameter to json_decode function and use the array notation:
将 true 作为第二个参数传递给 json_decode 函数并使用数组表示法:
$obj = json_decode($json_string2, true);
foreach ($obj['geometry'] as $key => $value) {
$lat = $value['location']['lat'];
$long = $value['location']['lng'];
}
回答by Abraham Tugalov
Try this:
$jsonArray = json_decode($response,true);
尝试这个:
$jsonArray = json_decode($response,true);
It's just, first you got to convert whole json string into array or object with json_decode
function, then work with structure.
只是,首先您必须将整个 json 字符串转换为带有json_decode
函数的数组或对象,然后再使用结构。