JSON 到 PHP 数组问题


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 的电流。 如果我尝试添加其他字段,它不会显示

回声$data["当前"]["日"];( 不工作 )

有人可以建议我如何显示两个频道 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'];
}
?>

我确实进行了编辑,因为还有其他错误,因为每条记录中都没有"当前"。

循环

$data引用和错误数组索引的冲突:

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'];
}