2016-09-23 94 views
-1

嗨,這個數組包含不止一個國家​​的事件,我怎麼能循環放出所有這些?如何通過數組循環?

$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"; 
    } 
+0

一種方法是使用'的foreach()'http://php.net/manual/en/control-structures.foreach.php –

+0

能否請您分享一些代碼,我是那種如果新手在此? – letsforum

+5

你也可以閱讀更多關於這個副本:http://stackoverflow.com/questions/4414623/loop-through-an-array-php –

回答

1
foreach($address_data as $row){ 
     print_r($row) 
} 
+0

更正,很長時間不使用PHP –

+0

它只返回一個結果,但必須返回2阿根廷和西班牙。 PLease的人幫我在這裏 – letsforum

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

這行只返回一個結果:$ address_data = $ jsondata-> results [0] - > address_components;必須循環這一個 – letsforum

0

$address_data實際上是對象的數組。使用foreach循環來遍歷數組並訪問每個對象的屬性是這樣的:

// your code 

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

我覺得忽略了答案的一件事剩下的就是你的結果是一個數組爲好。

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

它應該是'foreach($ jsondata-> results as $ result)'。 –

+0

你是如此正確,謝謝 – moorscode

+0

太棒了這項工作: \t 它應該是foreach($ jsondata-> results作爲$結果)如何讓這個國家陣列? – letsforum