【问题标题】:echo an array data from json decode从 json decode 回显数组数据
【发布时间】:2015-01-15 20:08:04
【问题描述】:

我想从 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'];
?>

带有 print_r ($input) 的演示;而不是回显http://phpad.org/run/1666334020

所以在我的主页中我想输出像这样http://codepen.io/anon/pen/jEEPMG.html

【问题讨论】:

  • $input['Servers']['ServersList'][0]['online']; 应该可以工作
  • 那行得通..谢谢..您可以发布为答案,以便我可以将其标记为答案。
  • print_r 输出如果显示正确会缩进。只需按照下一行的缩进即可。

标签: php arrays json


【解决方案1】:

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

我认为您正在尝试这样做:

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

【讨论】:

    【解决方案2】:

    在您在“lastChangedDate”上方发布的 json 中为 null 意味着您无法使用它访问它

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

    首先你应该找出为什么 lastChangedDate 为空。 $input['Servers']['lastChangedDate']['ServersList'][0]['online'];

    粗体文本是访问冲突的开始。 PHP 还应该向您输出类似“未定义索引:ServerList”的错误,因此您需要先填写 lastChangedDate 以进一步请求其内容

    可能是你想访问

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

    【讨论】:

    • 他不应该这样遍历,和NULL无关,因为结构是这样的:Servers->ServersList->等
    • 他在他的例子中调用 lastChangedDate 是 NULL,所以我认为他调用 lastChangedDate 只是一个错误
    • 我认为它在过去几年左右是空的,但我真的不知道为什么.. 因为我没有与那些开发人员联系.. 我是 php 新手所以我没有'真的不知道是否要调用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多