I have an json array like given below, what I want is to
parse through the array and get a value for corresponding
key .Eg SubAdministrativeAreaName
.I could have parsed it
like .
["AddressDetails"]['Country']['AdministrativeArea'] ['SubAdministrativeArea']['SubAdministrativeAreaName']
but the structure of array is not fixed , it may contain some other keys within which "SubAdmininstrativeArea" may be enclosed .
开发者_JS百科What I want is a php function that will search for a particular key name through multidimensional json array of any depth .
Any help would be appreciated .
"AddressDetails": {
"Accuracy": 6,
"Country": {
"AdministrativeArea": {
"AdministrativeAreaName": "Maharashtra",
"SubAdministrativeArea": {
"SubAdministrativeAreaName": "Parbhani",
"Thoroughfare": {
"ThoroughfareName": "SH217"
}
}
},
"CountryName": "India",
"CountryNameCode": "IN"
}
}
OK, different answer based on comment below:
function array_key_search_deep($needle, $haystack) {
$value = NULL;
if(isset($haystack[$needle])) {
$value = $haystack[$needle];
} else {
foreach($haystack as $node) {
if(is_array($node)) {
$value = array_key_search_deep($needle, $node);
if(!is_null($value)) {
break;
}
}
}
}
return $val;
}
Old Answer
This will allow you to traverse an unknown path in any array tree:
$path = array('AddressDetails', 'Country', 'AdministrativeArea', 'SubAdministrativeArea', 'SubAdministrativeAreaName');
$node = $json_object;
foreach($path as $path_index) {
if(isset($node[$path_index])) {
$node = $node[$path_index];
} else {
$node = NULL;
}
}
echo($node);
Thanks guys , what I made was a a solution like this
I finally found a simple solution myself For eg) To get "ThoroughfareName" make a call recursive_array_search($json_array,'ThoroughfareName') ; function recursive_array_search($arr,$jackpot) { foreach ($arr as $key => $value) { if(is_array($value)) { $val=recursive_array_search($value,$jackpot) ; return $val; } else { if($key==$jackpot) return $value; } } }
You could use JSONPath (XPath for JSON)
http://goessner.net/articles/JsonPath/
(with for instance the expression "$..SubAdministrativeAreaName")
EDIT: Haven't tested it, not sure how reliable it is.
精彩评论