get a deeper element which satisfies the condition

77 views Asked by At
    "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.

3

There are 3 answers

3
Martin Heralecký On BEST 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.

1
Malkhazi Dartsmelidze On

You can use array_filter to iterate over array without looping:



$postal_code_arrays = array_filter($arr, function($a){
  if(!isset($a['types'])) return false;

  // Or you can use another condition. i.e: if array only contains postal code
  if(in_array('postal_code', $a['types'])) {  
    return true;
  }
  
  return false;
});

This will return array which only contains last one in your array:

[
    [
        "long_name" => "GL50 1LR",
        "short_name" => "GL50 1LR",
        "types" => [
            "postal_code"
        ]
    ]
]
0
John V On

Try array_filter

$postCode = array_filter($arr["address_components"], function($v) {
    return in_array("postal_code", $v["types"]);
})[0]['long_name'];