2017-01-10 217 views
0

如何檢查對象中是否存在鄰域值?檢查對象中是否存在值

{ 
    "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; 
} 
+1

Anywhere的對象中的,或者在一個特定的地方? –

+1

類型仍然是一個數組,所以你不需要說類型[0] – Rob85

+0

只有一個地方:https://maps.googleapis.com/maps/api/geocode/json?latlng=30.560030000000,-97.691430000000 – santa

回答

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; 
    } 
} 
+2

雖然在技術上並不正確,但我懷疑這是如此直接的方法。一些循環可能是爲了... – deceze

+0

是的,這是一個擴展的例子。 – AbraCadaver

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

有沒有任何保證,價值將永遠在那個地方......? – deceze

+0

但基於他的代碼,它在address_components [2]中的保證是什麼,他正在尋找它,AbraCadavers的方式是更絕對的 – Rob85