Tashen Jazbi Tashen Jazbi - 4 months ago 36
JSON Question

json parsing in php returning Trying to get property of non-object error

i'm trying to parse a json string... before parsing i put my data in json format.. I've tried everything but no success... please help

here is my code..

$querys = "SELECT * FROM image_refrences WHERE building_id=''";
$rows = array();
$responce= array();
$data = $conn->query($querys);

while($row = $data->fetch_assoc()){
$json['images'][] = array('id' => $row['id'], 'url' => $row['image_file'], 'location' => $row['location'] );

}

$responce= json_encode($json, TRUE);
$rows=json_decode($responce,TRUE);

foreach ( $rows->images as $output ) {
echo $output->id;
}


my json string will look like that

{"images":[{"id":"1","url":"def6a9.jpg","location":""},{"id":"2","url":"def6a9.jpg","location":""},{"id":"3","url":"fullsize_distr.jpg","location":""}]}


please help me where i'm doing wrong.. thank you

Answer

Remove the second argument from this: $rows=json_decode($responce,TRUE);

With that true, you are decoding to a multidimensional array rather than an array of objects, and you are trying to access it using object syntax with $rows->images and $output->id.


Or instead, if you want to keep decoding it as an array, then keep the true argument and use array syntax to access the result:

foreach ( $rows['images'] as $output ) {
    echo $output['id'];
}

After making the changes, your code should be like this:

while($row = $data->fetch_assoc()){
    $json['images'][] = array('id' => $row['id'], 'url' => $row['image_file'], 'location' => $row['location'] );
}

$responce = json_encode($json);           // Remove TRUE
$rows = json_decode($responce);           // Remove TRUE

foreach ( $rows->images as $output ) {
    echo $output->id;
}

I may be making too many assumptions. I assume you are just experimenting with the json functions, because you are encoding to JSON and then immediately decoding. If you actually don't need JSON, you can skip all of that and just output the ids in your while loop.

while ($row = $data->fetch_assoc()){
    echo $row['id'];
}