【问题标题】:Loop through json-data循环通过 json-data
【发布时间】:2018-05-29 09:54:44
【问题描述】:

我有一个使用这种结构生成 JSON 数据的脚本。我试图循环出这是一个带有 PHP 的 HTML 列表,但现在做对了。

这是 JSON 的结构:

{
  "msg": [
    "msg text 1",
    "msg text 2",
    "msg text 3",
    "msg text 4",
    "msg text 5",
    "msg text 6"
  ]
}

我的 PHP 代码如下所示:

$json = file_get_contents('my_json_file');
$results = json_decode($json);
$array = (array)$results;

foreach ($array as $key => $item){
        echo "Key: ".$key." Item: ".$item;
}

这段代码的输出是:

Key: msg Item: Array

谁知道我必须编辑什么才能做到这一点?

【问题讨论】:

  • foreach ($array['msg'] as $key => $item) 应该可以满足您的需求吗?此外,将 true 添加到您的 json_decode 以成为 $results = json_decode($json, true); ,它将被解析为数组而不是对象
  • 您的代码工作正常。它将msg 显示为一个数组。您必须提供预期的输出才能更正您的代码。

标签: php json loops foreach


【解决方案1】:

您必须在 array['msg'] 上执行 foreach 以获取所有 msg 项。否则你将遍历主数组的所有属性(在这种情况下只有msg

$json = file_get_contents('my_json_file');
$results = json_decode($json);
$array = (array)$results;

foreach ($array['msg'] as $item){
        echo "Key: msg Item: ".$item;
}

输出将是:

Key: msg Item: msg text 1 
Key: msg Item: msg text 2
...

如果还想循环遍历主数组,想打印msg的内容,就得用print_r来打印数组的内容

$json = file_get_contents('my_json_file');
$results = json_decode($json);
$array = (array)$results;

foreach ($array as $key => $item){
    echo "Key: ".$key." Item: ".print_r($item, true);
}

输出将是:

Key: msg Item: array [
    "msg text 1",
    "msg text 2",
    ...
]

【讨论】:

    【解决方案2】:

    使用此示例代码。

        $json = '{
            "msg": [
            "msg text 1",
            "msg text 2",
            "msg text 3",
            "msg text 4",
            "msg text 5",
            "msg text 6"
        ]}';
    
        $results = json_decode($json);
        $array = $results->msg;
        foreach ($array as $key => $item){
            echo "Key: ".$key." Item: ".$item;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2019-12-19
      • 1970-01-01
      • 2021-03-29
      • 2018-03-13
      • 2011-08-07
      相关资源
      最近更新 更多