2013-10-03 74 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']; 
} 
?> 

我做编辑,因为因为没有在每个记录“当前”有一个其它的错误。