Reputation: 1068
I'm trying to parse a JSON string. Before parsing I put my data in JSON format, but I am getting a "trying to get property of non-object" error.
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 this:
{"images":[
{"id":"1","url":"def6a9.jpg","location":""},
{"id":"2","url":"def6a9.jpg","location":""},
{"id":"3","url":"fullsize_distr.jpg","location":""}
]}
Can someone help me find what I'm doing wrong?
Upvotes: 0
Views: 982
Reputation: 41810
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'];
}
Upvotes: 3