[英]PHP parsing multidimensional json array of any depth based on key
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 . 我有一个像下面给出的json数组,我想要的是通过数组解析并获取对应键的值。例如
SubAdministrativeAreaName
。我本可以像这样解析它。
["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 . 但是array的结构不是固定的,它可能包含其他一些关键字,其中可能包含“ SubAdmininstrativeArea”。
What I want is a php function that will search for a particular key name through multidimensional json array of any depth . 我想要的是一个php函数,它将通过任意深度的多维json数组搜索特定的键名称。
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 aa 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) 您可以使用JSONPath(JSON的XPath)
http://goessner.net/articles/JsonPath/ http://goessner.net/articles/JsonPath/
(with for instance the expression "$..SubAdministrativeAreaName") (例如,表达式为“ $ .. SubAdministrativeAreaName”)
EDIT: Haven't tested it, not sure how reliable it is. 编辑:尚未测试,不确定它的可靠性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.