[英]PHP parsing multidimensional json array of any depth based on key
我有一個像下面給出的json數組,我想要的是通過數組解析並獲取對應鍵的值。例如SubAdministrativeAreaName
。我本可以像這樣解析它。
["AddressDetails"]['Country']['AdministrativeArea'] ['SubAdministrativeArea']['SubAdministrativeAreaName']
但是array的結構不是固定的,它可能包含其他一些關鍵字,其中可能包含“ SubAdmininstrativeArea”。
我想要的是一個php函數,它將通過任意深度的多維json數組搜索特定的鍵名稱。
任何幫助,將不勝感激 。
"AddressDetails": {
"Accuracy": 6,
"Country": {
"AdministrativeArea": {
"AdministrativeAreaName": "Maharashtra",
"SubAdministrativeArea": {
"SubAdministrativeAreaName": "Parbhani",
"Thoroughfare": {
"ThoroughfareName": "SH217"
}
}
},
"CountryName": "India",
"CountryNameCode": "IN"
}
}
好的,根據以下評論提供不同的答案:
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;
}
舊答案
這將允許您遍歷任何數組樹中的未知路徑:
$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);
謝謝大家,我所做的就是這樣的解決方案
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; } } }
您可以使用JSONPath(JSON的XPath)
http://goessner.net/articles/JsonPath/
(例如,表達式為“ $ .. SubAdministrativeAreaName”)
編輯:尚未測試,不確定它的可靠性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.