0

I am trying to read a json object that is sent from a Rest Api call. However, i get a notice saying Undefined index. Is there anything i am missing ?

Notice: Undefined index subnet line 7

php

$response = file_get_contents('https://xyz:[email protected]/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 Answer 1

2

You're close:

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

Write it like you read it: you want the first item's subnet netmask and gateway.

                                 ^      ^          ^ 
                                [0] ['subnet'] ['netmask']
Sign up to request clarification or add additional context in comments.

2 Comments

thank you .. is it possible to determine the number of items in $data ? I was planning to run a for loop ? example $data[n]["subnet"]["gateway"] wondering hwo to determine the n ?
Sure. It's just a normal numerically keyed multidimensional array. count() and for loops work just fine. (As do foreach loops).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.