从json解码回显一个数组数据

时间:2014-11-18 15:16:06

标签: php arrays json

我想从json解码结果中回显一个数组数据,所以我尝试了file_get_contents和curl都可以工作。

这是我从服务器获得的响应,即json输出..

{"Servers": {
 "lastChangedDate": null,
 "ServersList":  [
    {
   "online": "The server is UP",
   "offline": "The server is DOWN",
   "maintainace": "The server is currently in maintenance mode",
   "location": "EU",
   "ip": "x.x.x.x"
  },
    {
   "online": "The server is UP",
   "offline": "The server is DOWN",
   "maintainace": "The server is currently in maintenance mode",
   "location": "US",
   "ip": "x.x.x.x"
  }
 ]
}}

现在解码后输出将是这样的数组..

Array (
    [Servers] => Array (
        [lastChangedDate] =>
        [ServersList] => Array (
            [0] => Array (
                [online] => The server is UP
                [offline] => The server is down
                [maintenance] => The server is currently in maintenance mode
                [location] => EU
                [ip] => x.x.x.x
            )
            [1] => Array (
                [online] => The server is UP
                [offline] => The server is DOWN
                [maintenance] => The server is currently in maintenance mode
                [location] => US
                [ip] => x.x.x.x
            )
        )
    )
)

这是我的PHP代码

<?php 
    $request = file_get_contents("test.json");
    $input = json_decode($request, true);
    echo $input['Servers']['lastChangedDate']['ServersList'][0]['online'];
?>

demo with print_r($ input);而不是echo http://phpad.org/run/1666334020

因此,在我的主页面中,我希望输出为http://codepen.io/anon/pen/jEEPMG.html

2 个答案:

答案 0 :(得分:1)

你在上面发布的json&#39; lastChangedDate&#39;为null表示您无法使用

访问它
$input['Servers']['lastChangedDate']['ServersList'][0]['online'];

首先你应该找到为什么lastChangedDate为null。 $输入[&#39;服务器&#39;] [&#39; lastChangedDate&#39;]的 [&#39; ServersList&#39;] [0] [&#39;在线&#39;]; < /强>

粗体文本是访问冲突开始的地方。 PHP还应输出一个错误,如&#34;未定义的索引:ServerList&#34;所以你需要先填写lastChangedDate以进一步请求其内容

可能是您想要访问

$input['Servers']['ServersList'][x]['online']; 

答案 1 :(得分:0)

条目$input['Servers'];$input['lastChangedDate'];位于数组的同一级别,因此您无法访问$input['Servers']['lastChangedDate']

我认为你正在尝试:

$input['Servers']['ServersList'][0]['online'];