检查对象中是否存在值

时间:2017-01-10 16:53:45

标签: php

如何检查对象中是否存在邻域值?

{
  "results" : [
  {
     "address_components" : [
        {
           "long_name" : "2900",
           "short_name" : "2900",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Ranch Road 620 North",
           "short_name" : "Ranch Rd 620 N",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Villas On Travis",
           "short_name" : "Villas On Travis",
           "types" : [ "neighborhood", "political" ]
        },
        {
           "long_name" : "Austin",
           "short_name" : "Austin",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Travis County",
           "short_name" : "Travis County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "Texas",
           "short_name" : "TX",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "78734",
           "short_name" : "78734",
           "types" : [ "postal_code" ]
        },
        {
           "long_name" : "2209",
           "short_name" : "2209",
           "types" : [ "postal_code_suffix" ]
        }
     ]
   }
 ]
}

我已经尝试了

if ($jsonarray->results[0]->address_components[2]->types == 'neighborhood') {
  $neighborhood = $jsonarray->results[0]->address_components[2]->long_name;
}

2 个答案:

答案 0 :(得分:2)

这是一个数组:

if (in_array('neighborhood', $jsonarray->results[0]->address_components[2]->types)) {
  $neighborhood = $jsonarray->results[0]->address_components[2]->long_name;
}

所以要检查所有内容,如果这是意图,如果只有一个neighborhood

foreach($jsonarray->results[0]->address_components as $array) {
    if (in_array('neighborhood', $array->types)) {
      $neighborhood = $array->long_name;
      break;
    }
}

或者获得所有找到的$neighborhood数组:

foreach($jsonarray->results[0]->address_components as $array) {
    if (in_array('neighborhood', $array->types)) {
      $neighborhood[] = $array->long_name;
    }
}

答案 1 :(得分:0)

ng test