I am trying to access a certain array inside of a JSON array, I can not seem to figure out how to access this data, any help would be appreciated!
Here is the JSON array: https://gist.github.com/anonymous/a37852a7436d31289390
It has no unique identifier, thats why I'm having trouble accessing it.
您应该简单地使用json_decode
函数,然后您将可以毫无问题地访问PHP数组
Suppose you want to access country name from this json data. and you have stored that json data in $geocode variable, Then you can do following. This will give you exact value of key whose key name is country, no matter on which index it is.
$output= json_decode($geocode);
foreach($output->results[0]->address_components as $key=>$val)
{
if($val->types[0]=='country' || $val->types[1]=='country')
{
$country=$output->results[0]->address_components[$key]->long_name;
}
}
If you are sure about index value you can acess it as below
$country =$output->results[0]->address_components[5]->long_name;
Hope this help :)
USe json_decode()
. It will give you an array value.
First check your json string in http://jsonlint.com it's invalid json.
Check the following example:
<?php
$jsonString = '{
"results": [
{
"address_components": [
{
"long_name": "Snip",
"short_name": "Snip",
"types": [
"street_number"
]
},
{
"long_name": "Snip",
"short_name": "Snip",
"types": [
"route"
]
},
{
"long_name": "Desert Ridge",
"short_name": "Desert Ridge",
"types": [
"neighborhood",
"political"
]
},
{
"long_name": "Snip",
"short_name": "Snip",
"types": [
"locality",
"political"
]
},
{
"long_name": "Snip",
"short_name": "Snip",
"types": [
"administrative_area_level_3",
"political"
]
}
]
}
]
}';
// Converting Json String to php jsonArray
$jsonArray = json_decode($jsonString);
// Initially its started with an object so you can't access like an array
//echo '<pre>';
//print_r($jsonArray);
// If you want to use results array check the following code
$results = $jsonArray->results;
echo '<pre>';
print_r($results);
/*
* If you want to access address_components key in first set of
* results then you need to use $resluts[0]->address_components[0]
* because every array have multiple objects, check the jsonArray
* once before accessing it wheather it is an array or object.
*/
print_r($results[0]->address_components[0]);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.