2013-04-27 126 views
1

我正在嘗試使用json和wunderground API請求一些數據。嘗試檢索數組時嘗試獲取非對象屬性的錯誤

當我使用此代碼時,它返回錯誤「消息:嘗試獲取非對象的屬性」。

<?php 

    $json_string = file_get_contents("http://api.wunderground.com/api/1e6a89f0a3aa092d/alerts/q/zmw:00000.1.16172.json"); 
    $parsed_json = json_decode($json_string); 
    $wColor = $parsed_json->{'alerts'}->{'attribution'}; 
    $wName = $parsed_json->{'alerts'}->{'wtype_meteoalarm'}; 
    echo "Severe weather alert ${wColor} expected ${wName} - MORE INFO"; 

?> 

數據是存在的,當我使用幾乎相同的示例代碼片段從文檔

<?php 
    $json_string = file_get_contents("http://api.wunderground.com/api/1e6a89f0a3aa092d/geolookup/conditions/q/IA/Cedar_Rapids.json"); 
    $parsed_json = json_decode($json_string); 
    $location = $parsed_json->{'location'}->{'city'}; 
    $temp_f = $parsed_json->{'current_observation'}->{'temp_f'}; 
    echo "Current temperature in ${location} is: ${temp_f}\n"; 
?> 

它的工作原理可以在這裏觀看然而...

http://api.wunderground.com/api/1e6a89f0a3aa092d/alerts/q/zmw:00000.1.16172.json

絕對好!我第一次請求失敗的原因是什麼?

+0

'alerts'是一個數組,並且沒有'attribution'屬性 – 2013-04-27 18:57:12

回答

1

的問題是在你檢索領域的方式。使用:

$wColor = $parsed_json->alerts[0]->attribution; 
    $wName = $parsed_json->alerts[0]->wtype_meteoalarm; 
0

試試這個

$alert = current($parsed_json->{'alerts'}); 
$wColor = $alert->{'attribution'}; 
$wName = $alert->{'wtype_meteoalarm'}; 
+0

什麼是'current'? – 2013-04-27 18:59:40

+0

http://php.net/manual/en/function.current.php只是PHP函數 – Ziumin 2013-04-27 19:01:04

+0

@JanDvorak'current'在這裏給出數組的第一個條目(因爲數組指針是第一個0,如果它不打算被改變) – bwoebi 2013-04-27 19:01:27

2

$parsed_json->alerts這裏是數字數組包含對象:

它的var_dump()「ED輸出:

object(stdClass)#1 (2) { 
    ["response"]=> ... 

    ["alerts"]=> 
    array(1) { 
    [0]=> 
    object(stdClass)#4 (15) { 
     ["type"]=> 
     string(3) "WRN" 
     ... 
    } 
    } 
} 

因此,使用:

$wColor = $parsed_json->alerts[0]->attribution; 
$wName = $parsed_json->alerts[0]->wtype_meteoalarm; 
+0

謝謝你。這得到了很好的解釋。 – ServerSideSkittles 2013-04-27 19:25:54

+0

@ServerSideSkittles你爲什麼接受別人的回答?我很困惑。 – bwoebi 2013-04-27 19:39:59

+1

@bwoebi:關於回答問題和幫助別人,不是嗎?看起來便宜,你抱怨OP選擇了另一個答案 - 這恰好也是正確的,順便說一句.. – 2013-04-27 21:01:14

相關問題