如何循环数组?

时间:2016-09-23 16:52:17

标签: 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;

    print_r( $address_data);

    //echo $address_data[3]->long_name;
  }
  else
  {
    echo "No Data Found Try Again";
  }

4 个答案:

答案 0 :(得分:1)

foreach($address_data as $row){
         print_r($row)
}

答案 1 :(得分:1)

我认为其余答案忽略的一点是你的结果也是一个阵列。

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

答案 2 :(得分:0)

使用foreach()是你能做的最好的事情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";
}

答案 3 :(得分:0)

$address_data实际上是一个对象数组。使用foreach循环遍历数组并访问每个对象的属性,如下所示:

// your code

foreach($address_data as $address){
    /*
    * $address->long_name
    * $address->short_name
    * $address->types[0]
    * $address->types[1]
    */
}