简体   繁体   English

使用数组从json文件获取数据

[英]Getting data from a json file with arrays

I'm having troubles to get specific data from a json file using the built-in php functions. 我在使用内置的php函数从json文件中获取特定数据时遇到了麻烦。 Let me show you some code : 让我给你看一些代码:

Json File : 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" }   ] }

My php code : 我的PHP代码:

$json= file_get_contents("myfile.json");
$data =  json_decode($json, true);
$voter1 = $data['votes']->nickname;
echo $firstvoter;

I had this code working on a very basic json code without arrays. 我让这段代码在没有数组的非常基本的json代码上工作。 But something is wrong here because I can't get the nicknames of the voters. 但是这里有些问题,因为我无法获得选民的昵称。

I'm just a little bit confused, so what I wanna do is picking up the nicknames of the voters and then I'll put them on a table using html. 我只是有点困惑,所以我想做的是拿起选民的昵称,然后使用html将它们放在桌子上。

I hope I get a detailed answer so I can understand some of the confusing stuff. 希望我得到详细的答案,以便我能理解一些令人困惑的内容。

you need to get array to json object. 您需要将数组获取到json对象。 hear "votes" is json object so $data['votes'][0] is return first array see code... 听到“ votes”是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"];

?>

After converting into json Decode you array make look like this, 转换为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
                )

        )

)

In this you need the nickname: 在此您需要昵称:

foreach ($jsonData['votes'] as $key => $value) {
    echo "Nickname : ". $value['nickname']."<br/>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM