-2

For some reason I am not getting the expected output from json_decode. The JSON string comes back from an API call and the first part of the string looks as follows:

{"droplets":[{"id":67892618,"name":"NEW-TEK","memory":8192,"vcpus":4,"disk":20,blah blah blah

Here is the relevant portion of the code I am using:

function Test() {
    $ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
    $json = curl_exec($ch);
    $obj = json_decode($json,true);
    echo 'Just making sure everything is working up till here!';
    echo "\n\n";
    $id = $obj->{'id'};
    echo 'Droplet ID: ';
    echo $id;
    exit;
}

Ignore all the random echo lines and new line stuff. Just making the example easy to read. As you can see, nothing is getting pulled out of the array and echoed.

enter image description here

Atomiklan
  • 5,164
  • 11
  • 40
  • 62
  • `$obj = json_decode($json,true);` this gives you an array, not an object – Patrick Q Oct 26 '17 at 19:27
  • That's what I was expecting. I wanted to pull the id out of the array. I just named the variable obj. – Atomiklan Oct 26 '17 at 19:28
  • Not according to your code. You're accessing it as if it's an object (and referring to a variable called `$obj`, implying you think it is an object) – Patrick Q Oct 26 '17 at 19:29
  • Yeah I just was not experienced enough to know what I was doing... Physicist here, not a programmer :( – Atomiklan Oct 26 '17 at 19:31
  • Also possible dupe of https://stackoverflow.com/questions/30680938/how-can-i-access-an-array-object since OP claimed to know an array was being returned – Patrick Q Oct 26 '17 at 19:33

1 Answers1

3

Since you're using $obj = json_decode($json,true); the true makes the output an array, not an object which you try to use here $id = $obj->{'id'}; Here is what the array looks like:

Array
(
    [droplets] => Array
        (
            [0] => Array
                (
                    [id] => 67892618
                    [name] => NEW-TEK
                    [memory] => 8192
                    [vcpus] => 4
                    [disk] => 20
                )

        )

)

Instead use $id = $obj['droplets'][0]['id']; as you have to identify the segment of the array you want to look at.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119