-1

Hi this array contains more than one occurrences of the country how can I loop and out put all of them?

$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=cordoba';




  $json = @file_get_contents($url);

  $jsondata = json_decode($json);
  $status = $jsondata->status;
  $address = '';
  if($status == "OK")
  {
    $address_data = $jsondata->results[0]->address_components;

    print_r( $address_data);

    //echo $address_data[3]->long_name;
  }
  else
  {
    echo "No Data Found Try Again";
  }
letsforum
  • 27
  • 5
  • One way would be to use `foreach()` http://php.net/manual/en/control-structures.foreach.php – M. Eriksson Sep 23 '16 at 16:54
  • Could you please share some code I am kind if newbie in this? – letsforum Sep 23 '16 at 16:57
  • 5
    You can also read more on this duplicate: http://stackoverflow.com/questions/4414623/loop-through-an-array-php – M. Eriksson Sep 23 '16 at 16:57
  • 2
    There are plenty of examples in the links I provided. (A suggestion, try Google before asking. It will go much faster) – M. Eriksson Sep 23 '16 at 16:58
  • OK gonna test it! – letsforum Sep 23 '16 at 16:59
  • Just a side note, you're suppressing errors by appending `@` in front of your `file_get_contents()` (which means that if the URL fails, you won't get any error), but then run both the `json_encode()` and `$status = $jsondata->status` without any checks. The last one will definitely throw an error if the URL failed to start with, since it won't actually be an object.. – M. Eriksson Sep 23 '16 at 17:11

4 Answers4

1
foreach($address_data as $row){
         print_r($row)
}
Steve Fox
  • 46
  • 3
1

I think the one thing the rest of the answers overlooked is that your results are an array as well.

if($status == "OK")
{
  foreach ($jsondata->results as $result) {
    $address_data = $result->address_components;
    echo $address_data[3]->long_name;
  }
}
moorscode
  • 801
  • 6
  • 13
0

Using foreach() is the best thing you can do php.net/manual/en/control-structures.foreach.php

$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=cordoba';

$json = @file_get_contents($url);

$jsondata = json_decode($json);
$status = $jsondata->status;
$address = '';
if($status == "OK")
{
  $address_data = $jsondata->results[0]->address_components;

 foreach ($address_data as $address) {
     echo $address->long_name;
  }
}
else
{
  echo "No Data Found Try Again";
}
CodingNagger
  • 1,178
  • 1
  • 11
  • 26
  • This line only returns one result: $address_data = $jsondata->results[0]->address_components; have to loop this one – letsforum Sep 23 '16 at 17:04
0

$address_data is actually an array of objects. Use a foreach loop to loop through the array and access each object's property like this:

// your code

foreach($address_data as $address){
    /*
    * $address->long_name
    * $address->short_name
    * $address->types[0]
    * $address->types[1]
    */
}
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37