[英]JSON to PHP array issue
我试图使用PHP解码将下面的JSON字符串解析为一个数组,以便可以从文件中提取两个通道的当前日期和日期。
我的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
)
)
)
)
有人可以为此提供任何帮助吗?
谢谢
变量$ data发生冲突:
用于存储数据,并在foreach循环中使用。 在foreach中重命名$ data变量,例如:
<?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'];
}
?>
我进行了编辑,因为还有另一个错误,因为每个记录中都不存在“当前”信息。
foreach ($data['channels'] as $chanel)
{
echo $chanel[0]['current'];
echo $chanel[1]['day'];
}
循环中$data
引用冲突和数组索引错误:
foreach ($data['channels'] as $channel)
{
echo $channel[0]['current'];
echo $channel[1]['day'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.