阅读json并将其放入php中的var

时间:2016-02-07 19:48:21

标签: php json

我想读出这个json:

{ "name":"lexodexo", 
  "address":"lexodexo.de", 
  "port":"19132", 
  "month":"201602", 
  "voters": [ 
              { "nickname":"Henning", 
                 "votes":"6" 
               },
               { "nickname":"maxinator ", 
                 "votes":"5" 
               },
               { "nickname":"Blaubaer", 
                 "votes":"5" 
               }, 
               { "nickname":"Troll_Cyborg", 
                 "votes":"5" 
               }, 
               { "nickname":"OMG_ITS_INTOXx_", 
                 "votes":"2" } 
             ] 
}

最后看起来应该是这样的: 亨宁:6 maxinator:5 Blaubaer:5

我该怎么做?

2 个答案:

答案 0 :(得分:1)

JSON字符串是一个包含选民数组的对象。

不要使用,true中的json_decode()参数,然后按预期获得原始对象。

这会显示数组。

<?php 
    $string = file_get_contents("minecraftpocket-servers.com/api/… ");
    $json = json_decode($string); 

    foreach ( $json->voters as $voter ) {
        echo $voter->nickname . ' = ' . $voter->votes . '<br>';
?>

答案 1 :(得分:0)

请根据您的要求查看以下代码段:

<?php
$jsonString =   '{ "name":"lexodexo", 
  "address":"lexodexo.de", 
  "port":"19132", 
  "month":"201602", 
  "voters": [ 
              { "nickname":"Henning", 
                 "votes":"6" 
               },
               { "nickname":"maxinator ", 
                 "votes":"5" 
               },
               { "nickname":"Blaubaer", 
                 "votes":"5" 
               }, 
               { "nickname":"Troll_Cyborg", 
                 "votes":"5" 
               }, 
               { "nickname":"OMG_ITS_INTOXx_", 
                 "votes":"2" } 
             ] 
}';

$jsonObj = json_decode($jsonString);
foreach ($jsonObj->voters as $result)
{
    $nickname = $result->nickname;
    $votes = $result->votes;

    echo $nickname."  ".$votes."<br>";
}
?>

上面的代码将输出:

Henning 6
maxinator 5
Blaubaer 5
Troll_Cyborg 5
OMG_ITS_INTOXx_ 2

希望这适合你!