Reputation: 407
I have a JSON object like below, which is stored in a variable called $product
.
{"id":30}
When I try to access the stored value though, I get the following error:
Trying to get property of non-object
Here is what I am doing:
echo $product->id;
Alright folks, sorry for the wild goose chase. Apparently $products
was an array and not a JSON data, which is really odd because print_r($products)
and echo $products
gave different results.
The results can be viewed here:
I am using Laravel, and usually laravel returns a nice JSON object from an SQL query, I must have changed something somewhere, which is why this happened. Thanks.
Upvotes: 1
Views: 95
Reputation: 64
The first examples are working for me, make sure you PHP is supporting the json_decode() function. Or you could try this:
$product = '{"id":30}';
$t = json_decode($product, true);
echo $t["id"];
Passing the true value converts it to an array instead.
Upvotes: 0
Reputation: 107
Trying below sample :
<?php
$product = '{"id": 30}';
$obj = json_decode(json_encode($product)); // or json_decode(json_encode($product), true);
echo $obj->{'id'}; // or echo $obj->id
?>
Upvotes: 0
Reputation: 1649
You could use json_decode to your object.
Takes a JSON encoded string and converts it into a PHP variable.
usage:
print_r(json_decode($obj, true));
var_dump(json_decode($obj));
Upvotes: 0
Reputation: 9474
Try following json_decode function
$product = '{"id":30}';
$t = json_decode($product);
echo $t->id;exit;
Upvotes: 1