如何解析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 />";
}
}
答案 0 :(得分:3)
你必须使用[]代替{}来改变你的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" }
]
答案 1 :(得分: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" }
]
(看方括号)
“[]”括号表示LIST,而“{}”表示对象。 它们之间的区别在于对象包含“key”:“value”对,而list返回没有键的项
答案 2 :(得分:0)
[
{ "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
希望这会对你有所帮助, 祝你好运!