2017-06-04 32 views
1

我構建解碼JSON文件天氣應用程序(在這裏找到:http://api.openweathermap.org/data/2.5/forecast?q=Helsinki&appid=77f5e3fbc99649054660f82f871220f4&units=metric如何使用PHP導航JSON層次結構?

我遇到的問題,在我的PHP代碼導航JSON文件,以正確選擇tempature。

我需要做list->1->main->temp但這會在PHP中引發一個數字錯誤。我如何正確設置導航?

echo "<form id='searchform' method='POST' action='https://projekt2-sofiamusick.c9users.io/wordpress/prognos/'> 
Search: <input type='text' name='searchquery' placeholder='Search the forum' /> 
<input class='sendbutton_search' type='submit' name='search' value='>>' /> 
</form>"; 

if (isset($_POST['search'])){ 

$cityz = $_POST['searchquery']; 
echo "<br>"; 
echo "<div id=apithing>"; 
$data = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?q=$cityz&appid=77f5e3fbc99649054660f82f871220f4&units=metric"); 
$jsonObject = json_decode($data, JSON_NUMERIC_CHECK); 
json_encode(array('list' => (int)$jsonObject)); 
$list = $jsonObject->list; 
$number = $jsonObject->'1'; 
$mains = $jsonObject->main; 
echo $mains; 
+0

嘗試:'list [0] - > main-> temp'列表將是一個數組 –

回答

2

如果您使用的是JSON_NUMERIC_CHECK,則表示您的數據爲數組。
如果你想獲得第一要素,只要使用$jsonObject['list'][0]

沒有JSON_NUMERIC_CHECK,存在stdClass的數據,並且第一個元素,你可以用$jsonObject->list{0}

+0

非常感謝,這解決了這個問題! – Shawn

0

讓你可以實現像這樣

$data = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?q=Helsinki&appid=77f5e3fbc99649054660f82f871220f4&units=metric"); 
$jsonObject = json_decode($data); 
if($jsonObject->cod == '200' && count($jsonObject->list) > 0){ 
    foreach ($jsonObject->list as $jlk => $jlv) { 
    $dt = $jlv->dt; 
    $main = $jlv->main; 
    // your rest of logic 
    } 
} 

如果你想你可以看到你的數據是這樣的:

echo '<pre>'; 
    var_dump($jsonObject); 
    echo '</pre>'; 
    die; 

在哪裏可以看到對象,意味着您必須使用「 - >」來訪問,並且在哪裏看到數組,在那裏使用數組的鍵來獲取該值。

如果有其他疑問,請隨時詢問。