0

convert REST response in JSON to PHP arrray

Set the following up but got error =

Trying to get property of non-object in C:......

our JSON looks like

{
    "craneIDs": [{
        "craneID": "R01"
    }, {
        "craneID": "R02"
    }, {
        "craneID": "R04"
    }, {
        "craneID": "R08"
    }, {
        "craneID": "R09"
    }, {
        "craneID": "R10"
    }, {
        "craneID": "R16"
    }, {
        "craneID": "TC01"
    }, {
        "craneID": "T06"
    }, {
        "craneID": "T08"
    }, {
        "craneID": "T08/2"
    }, {
        "craneID": "T12"
    }]
}

after

$craneids_url   = 'http://...........';
$craneids_json  = file_get_contents($craneids_url);
$craneids_array = json_decode($craneids_json, true);
$i              = 0;
/* Error on following line */
while ($craneids_array->{'craneIDs'}[$i]) {
    print_r($craneids_array->{'craneIDs'}[$i]->{'craneID'});
    echo "<br />";
    $i++;
}
Rahul
  • 18,271
  • 7
  • 41
  • 60

3 Answers3

0

You can directly write without string,

// true return raw array but your syntax is for object
$craneids_array = json_decode($craneids_json);
$i =0;
// run while until there is value for craneIDs
while (isset($craneids_array->craneIDs[$i])) {
    print_r($craneids_array->craneIDs[$i]->craneID);
    echo "<br />";
    $i++;
}

Demo

Output:-

R01<br />R02<br />R04<br />R08<br />R09<br />R10<br />R16<br />TC01<br />T06<br />T08<br />T08/2<br />T12<br />
Rahul
  • 18,271
  • 7
  • 41
  • 60
0

With json_decode($craneids_json, true); you get an array.

Try:

foreach ($craneids_array['craneIDs'] as $craneIDs) {
        print_r($craneIDs['craneID']);
        echo "<br />";
    }
Manzolo
  • 1,909
  • 12
  • 13
0

The problem with the code you provided is that craneIDs is not a property of the object returned by json_decode, but it is a key. The following works:

//Replace $craneids_array->{'craneIDs'} with $craneids_array['craneIDs']

while ($craneids_array['craneIDs'][$i]) { 
    print_r($craneids_array['craneIDs'][$i]['craneID']);
    echo "<br />";
    $i++;
}

Working example here

Enbee
  • 128
  • 9