Skip to content
Advertisement

get a deeper element which satisfies the condition

    "address_components": [
    {
        "long_name": "8",
        "short_name": "8",
        "types": [
            "street_number"
        ]
    },
    {
        "long_name": "Promenade",
        "short_name": "Promenade",
        "types": [
            "route"
        ]
    },
    {
        "long_name": "Cheltenham",
        "short_name": "Cheltenham",
        "types": [
            "postal_town"
        ]
    },
    {
        "long_name": "Gloucestershire",
        "short_name": "Gloucestershire",
        "types": [
            "administrative_area_level_2",
            "political"
        ]
    },
    {
        "long_name": "England",
        "short_name": "England",
        "types": [
            "administrative_area_level_1",
            "political"
        ]
    },
    {
        "long_name": "United Kingdom",
        "short_name": "GB",
        "types": [
            "country",
            "political"
        ]
    },
    {
        "long_name": "GL50 1LR",
        "short_name": "GL50 1LR",
        "types": [
            "postal_code"
        ]
    }
],

Need to get the postal_code value, which is the value of long_name with types=postal_code. In the api result,it seems types itself is an array. Looping and finding out is a bad method. also array_search also don’t work. Can anybody help me.

Advertisement

Answer

Just loop through the array and find an item with the postal code:

foreach ($arr["address_components"] as $item) {
    if (in_array("postal_code", $item["types"])) {
        echo $item["long_name"];
    }
}

I’ll leave error handling to you.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement