2013-10-03 75 views
0

我試圖使用PHP解碼來解析我的JSON字符串到一個數組中,這樣我就可以從文件中提取兩個通道的當前日期。JSON到PHP數組問題

我的JSON文件owl_output.json樣子..

{"channels":{"0":[{"current":1288,"units":"w"},{"day":31278.57,"units":"wh"}],"1": [{"current":660,"units":"w"},{"day":9191.11,"units":"wh"}]}} 

我'永遠只能得到一個結果顯示,PHP代碼我設法得到工作低於

<?php 
$string = file_get_contents('owl_output.json'); 
$data = json_decode($string,true); 
print_r($json); 
foreach ($data['channels']['0'] as $data) 
{ 
    echo $data ['current']; 
} 
?> 

這隻顯示通道0的當前電流。如果我嘗試添加其他字段,則不會顯示

echo $ data ['current'] ['day']; (不起作用)

有人可以告訴我如何顯示當前和這兩個頻道的日期0 & 1?

我的目標是在最後的html頁面中顯示此內容並繼續輪詢json文件?

它顯示陣列低於

Array 
(
    [channels] => Array 
     (
      [0] => Array 
       (
        [0] => Array 
         (
          [current] => 1288 
          [units] => w 
         ) 

        [1] => Array 
         (
          [day] => 31278.57 
          [units] => wh 
         ) 

       ) 

      [1] => Array 
       (
        [0] => Array 
         (
          [current] => 660 
          [units] => w 
         ) 

        [1] => Array 
         (
          [day] => 9191.11 
          [units] => wh 
         ) 

       ) 

     ) 

) 

任何人都可以提供任何與此幫助?

感謝

+0

您應該遍歷'$數據[ '渠道']','不是$數據[ '渠道'] [0]'。 –

回答

0

在環路和壞的數組索引$data參考衝突:

foreach ($data['channels'] as $channel) 
{ 
    echo $channel[0]['current']; 
    echo $channel[1]['day']; 
} 
+0

這工作,但我想顯示每個結果的新行上的所有結果。目前這一行顯示在屏幕上。 – user2843830

+0

如果你使用html輸出,使用標籤格式,如'
',如果輸出是原始文本,使用'「\ n」'去換行。 – Koryonik

+0

再次感謝您的工作。如果我想查詢owl_output.js文件。呼叫在代碼中應該在哪裏? <?php $ string = file_get_contents('test/owl_output.js'); $ data = json_decode($ string,true); print_r($ json); foreach($ data ['channels'] as $ channel) { echo「Current」。 $信道[0] [ '當前']。 「
」; 回聲「日」。 $信道[1] [ '天']。 「
」; } 的setInterval(函數(){$ .getJSON( 「測試/ owl_output.js」 功能(數據){// 更新與新的數據 視圖});} ,5000); } ?> – user2843830

0
foreach ($data['channels'] as $chanel) 
{ 
    echo $chanel[0]['current']; 
    echo $chanel[1]['day']; 
} 
1

變量$的數據是相互矛盾的:

用於存儲數據,並在foreach循環使用。重命名$ data變量在foreach例如:

<?php 
$string = file_get_contents('owl_output.json'); 
$data = json_decode($string,true); 
print_r($json); 
foreach ($data['channels'] as $channel) 
{ 
    echo $channel[0]['current']; 
    echo $channel[1]['day']; 
} 
?> 

我做編輯,因爲因爲沒有在每個記錄「當前」有一個其它的錯誤。