我在使用内置的php函数从json文件中获取特定数据时遇到了麻烦。 让我给你看一些代码:
Json文件:
{"votes": [ { "date":"November 3rd, 2017 10:08 PM EST", "timestamp":1509743288, "nickname":"Th3ProHack3R", "claimed":"0" }, { "date":"November 3rd, 2017 10:06 PM EST", "timestamp":1509743160, "nickname":"TheKing", "claimed":"0" }, { "date":"November 3rd, 2017 09:45 PM EST", "timestamp":1509741902, "nickname":"some0ne", "claimed":"0" } ] }
我的PHP代码:
$json= file_get_contents("myfile.json");
$data = json_decode($json, true);
$voter1 = $data['votes']->nickname;
echo $firstvoter;
我让这段代码处理一个没有数组的非常基本的json代码。但这里出了点问题,因为我无法获得选民的绰号。
我只是有点困惑,所以我想做的是拿起选民的绰号,然后我会用html将它们放在桌子上。
我希望我得到一个详细的答案,这样我就能理解一些令人困惑的东西。
答案 0 :(得分:0)
你需要将数组转换为json对象。听到"投票"是json对象所以$ data [' votes'] [0]返回第一个数组看代码......
<?php
$json= file_get_contents("myfile.json");
$data = json_decode($json, true);
$voter1 = $data['votes'][0];
$voter2 =$data['votes'][1];
print_r( $voter1);
echo "<br>".$voter1["nickname"];
echo "<br>".$voter2["nickname"];
?>
答案 1 :(得分:0)
转换成json Decode后,你的数组看起来像这样,
Array
(
[votes] => Array
(
[0] => Array
(
[date] => November 3rd, 2017 10:08 PM EST
[timestamp] => 1509743288
[nickname] => Th3ProHack3R
[claimed] => 0
)
[1] => Array
(
[date] => November 3rd, 2017 10:06 PM EST
[timestamp] => 1509743160
[nickname] => TheKing
[claimed] => 0
)
[2] => Array
(
[date] => November 3rd, 2017 09:45 PM EST
[timestamp] => 1509741902
[nickname] => some0ne
[claimed] => 0
)
)
)
在这里你需要昵称:
foreach ($jsonData['votes'] as $key => $value) {
echo "Nickname : ". $value['nickname']."<br/>";
}