arrays - PHP JSON trying to get property of non-object error when looping -
i error notice: trying property of non-object
each time array @ index 0.
but works if there more 1 value in array.
$jsonurl = "https://example.org/json_response/"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json, true); foreach ( $json_output $output ) { echo $output->id; }
using var_dump($json_output);
returns data.
edited
array (size=2) 'id' => string 'xyue78ee9es' (length=10) 'username' => string 'peesbee' (length=7)
but throws error when try accessing variable echo $output->id;.
as have said in comments above, once you've set json_decode
flag true
, in turn, you'll array instead of object.
following in comments:
can show me $json_output array ? – prakash
@prakash, array (size=1) 'id' => string 'xyue78ee9es' (length=10) – user123451
it seems normal flat array, treat such. actually, wouldn't need foreach anymore. can access individual elements directly:
echo $json_output['id']; echo $json_output['username'];
if still use foreach
, it'll traverse first level, wouldn't need put index anymore:
foreach($json_output $output) { echo $output; // no need ['id'] or ->id anymore // strings on $output }
if you'd restrict elements getting echoed inside foreach
loop, simple if
statement testing keys should suffice:
foreach($json_output $key => $output) { if($key === 'id') { echo $output; // echoes id } }
Comments
Post a Comment