santa
santa

Reputation: 12512

Check if value present in object

How do I check if neighborhood value is present in the object?

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

I've tried

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

Upvotes: 0

Views: 64

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

It's an array:

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

So to check them all, if's that's the intent, if there will only be one neighborhood:

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

Or to get a $neighborhood array of all found:

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

Upvotes: 2

Rob85
Rob85

Reputation: 1729

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

Upvotes: 0

Related Questions