代码之家  ›  专栏  ›  技术社区  ›  Geethu

得到满足条件的更深层次的元素

  •  0
  • Geethu  · 技术社区  · 5 年前
        "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"
            ]
        }
    ],
    

    3 回复  |  直到 5 年前
        1
  •  2
  •   Martin Heralecký    5 年前

    只需在数组中找到一个邮政编码:

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

        2
  •  2
  •   Malkhazi Dartsmelidze    5 年前

    你可以用 array_filter 在数组上迭代而不循环:

    
    
    $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;
    });
    

    这将返回数组,该数组只包含数组中的最后一个:

    [
        [
            "long_name" => "GL50 1LR",
            "short_name" => "GL50 1LR",
            "types" => [
                "postal_code"
            ]
        ]
    ]
    
        3
  •  0
  •   John V    5 年前

    尝试数组过滤器

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