无法使用PHP解码json对象?

时间:2014-09-23 19:43:06

标签: php arrays json

我正在尝试读取从Rest Api调用发送的json对象。但是,我收到一条说明Undefined index的通知。我有什么遗失的吗?

注意:未定义的索引子网第7行

PHP     

$response = file_get_contents('https://xyz:aldkhfuycdhjrrirfjfjkfj@api.softlayer.com/rest/v3/SoftLayer_Account/IpAddresses.json'); 

$data = json_decode($response,true);

echo "Gateway: ".$data["subnet"][0]["gateway"];
echo "NetMask: ".$data["subnet"][0]["netmask"];

echo "Done";
?>

IpAddresses.json

[
   {
      "id":12345,
      "subnet":{
         "netmask":"255.255.255.255",
         "gateway":"192.168.255.255"
      }
   },
   {
      "id":56789,
      "subnet":{
         "netmask":"255.255.255.255",
         "gateway":"192.168.255.255"
      }
   }
]

1 个答案:

答案 0 :(得分:2)

你关闭了:

echo "Gateway: ".$data[0]["subnet"]["gateway"];
echo "NetMask: ".$data[0]["subnet"]["netmask"];

像你读的那样写它:你想要第一个项目的子网网络掩码和网关。

                                 ^      ^          ^ 
                                [0] ['subnet'] ['netmask']