开发者

PHP parsing multidimensional json array of any depth based on key

开发者 https://www.devze.com 2023-03-25 17:20 出处:网络
I have an json array like given below, what I want is to parse through the array and get a value for corresponding

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消