Reputation: 1994
I know similar sort of questions been asked before. But reason I'm asking is because I have tried many of those solution provided here in those questions, but nothing seemed to work for me. :( Let's say I have tried these questions: 1 2 3
Background
I'm calling to a RESTAPI and get data in json format.
$apiResult = connect_to_api($link); // function works fine
echo '<pre>';
echo print_r(json_decode($apiResult));
echo '</pre>';
when I print, I get following result:
stdClass Object
(
[id] => 91
[name_1] => city name
[name_2] => area name
[name_3] => municipality
[web] => www.example.com
)
Problem Scope
When I try to access only value of id
it says trying to get non-object property. Like for example I tried
echo $apiResult->id;
foreach($apiResult as $result){
echo $result->id;
}
Nothing did really work. Don't know where am I going wrong. Any help or suggestion is appreciated. Thanks in advance.
Upvotes: 0
Views: 2104
Reputation: 94672
In your foreach you are basically processing over the objects properties and getting the properties returned as a name => value pair.
So in this statement of your :-
foreach($apiResult as $result){
echo $result->id;
}
$result
will be 91
, city name
, area name
.... i.e. the values of each property and not an object at all.
So for example if you coded the foreach like this it would demonstrate this
// foreach over the object
foreach ( $apiResult as $property => $Value ) {
echo "Property Name = $property";
echo " Property Value = $value <br>";
}
But this is unlikely to be what you want to do, I assume you just want to get at the properties by name, so use
echo $apiResult->id;
echo $apiResult->name_1;
etc
Upvotes: 1
Reputation: 24276
did you try to decode the json before calling the object property?
$apiResult = json_decode(connect_to_api($link));
echo $apiResult->id;
Upvotes: 3