首页 > 解决方案 > 得到满足条件的更深的元素

问题描述

    "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"
        ]
    }
],

需要获取postal_code的值,也就是long_name中types=postal_code的值。在 api 结果中,似乎类型本身就是一个数组。循环查找是一种不好的方法。array_search 也不起作用。有谁能够帮我。

标签: phplaravellaravel-5.8

解决方案


您可以使用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"
        ]
    ]
]

推荐阅读