【问题标题】:how to parse following json in php如何在php中解析以下json
【发布时间】:2014-04-07 20:50:34
【问题描述】:

如何在php中解析下面的json

[
 { "user":"John", "age":22, "country":"United States" },
 { "user":"Will", "age":27, "country":"United Kingdom" },
 { "user":"Abiel", "age":19, "country":"Mexico" },
 { "user":"Rick", "age":34, "country":"Panama" },
 { "user":"Susan", "age":23, "country":"Germany" },
 { "user":"Amy", "age":43, "country":"France" }
]

我使用以下代码,但它没有工作

$jsonData = file_get_contents("http://localhost/attendance1/a.json");
$phpArray = json_decode($jsonData, true);
echo $phpArray;
foreach ($phpArray as $key => $value) {
    echo "<h2>$key</h2>";
    foreach ($value as $k => $v) {
        echo "$k | $v <br />";
    }
}

【问题讨论】:

  • 这不是有效的 JSON。
  • 数组应该用[ ... ]包围,而不是{ ... }
  • 这不是一个有效的 JSON 字符串。
  • 使用更正后的 JSON,您的脚本可以为我工作。
  • 现在可以工作了..谢谢

标签: php foreach json


【解决方案1】:

这不是一个有效的 JSON 格式,试试这个:

[
 { "user":"John", "age":22, "country":"United States" },
 { "user":"Will", "age":27, "country":"United Kingdom" },
 { "user":"Abiel", "age":19, "country":"Mexico" },
 { "user":"Rick", "age":34, "country":"Panama" },
 { "user":"Susan", "age":23, "country":"Germany" },
 { "user":"Amy", "age":43, "country":"France" }
]

(看方括号)

“[]”括号表示一个列表,而“{}”表示一个对象。 它们之间的区别在于对象包含“键”:“值”对,而列表返回没有键的项目

【讨论】:

    【解决方案2】:

    您必须使用 [ ] 而不是 { } 将您的 json 主要项目更改为数组(而不是对象)。

    [
     { "user":"John", "age":22, "country":"United States" },
     { "user":"Will", "age":27, "country":"United Kingdom" },
     { "user":"Abiel", "age":19, "country":"Mexico" },
     { "user":"Rick", "age":34, "country":"Panama" },
     { "user":"Susan", "age":23, "country":"Germany" },
     { "user":"Amy", "age":43, "country":"France" }
    ]
    

    【讨论】:

      【解决方案3】:
      [
       { "user":"John", "age":22, "country":"United States" },
       { "user":"Will", "age":27, "country":"United Kingdom" },
       { "user":"Abiel", "age":19, "country":"Mexico" },
       { "user":"Rick", "age":34, "country":"Panama" },
       { "user":"Susan", "age":23, "country":"Germany" },
       { "user":"Amy", "age":43, "country":"France" }
      ]
      

      格式是这样的 一个数组

      $array = [3,5,7,4]
      

      打印出来的样子

      Array ( [0] => 3 [1] => 5 [2] => 7 [3] => 4 ) 
      

      并且元素访问了$array{index} 以同样的方式使用循环,您应该访问元素,然后您可以使用函数 json_decode。

      $object = json_decode($element_of_array)
      

      使用该对象返回一个对象,您可以从 json 元素访问数据。

      $object->user
      $object->age
      

      希望这对你有帮助, 祝你好运!

      【讨论】:

        猜你喜欢
        • 2015-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-31
        • 2016-10-08
        • 2013-04-06
        • 2014-04-16
        • 1970-01-01
        相关资源
        最近更新 更多