2015-09-04 60 views
-1

如何循環訪問此json文件?使用PHP循環到JSON文件中

{ 
    "AF": "Afghanistan", 
    "ZA": "Afrique du Sud", 
    "AL": "Albanie", 
    .... 
} 

我想:

$json = json_decode('country.json'); 
foreach($json as $country){ 
    echo '<option '.$country[0].'>'.$country[1].'</option>'; 
} 

回答

2

默認情況下json_decode給你的對象。我建議告訴它給你一個數組。

然後你可以遍歷它並獲得鍵/值。

// You need to get the JSON string first 
$jsonFile = file_get_contents('country.json'); 

// json_decode expects the JSON data, not a file name 
// the `true` tells it to give you an array 
$json = json_decode($jsonFile, true); 
foreach($json as $code=>$country){ 
    echo '<option value="'.$code.'">'.$country.'</option>'; 
}