0

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.

Community
  • 1
  • 1
Abu Shumon
  • 1,834
  • 22
  • 36

2 Answers2

3

did you try to decode the json before calling the object property?

$apiResult = json_decode(connect_to_api($link));
echo $apiResult->id;
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
  • @Mihai, yes I did decode before calling the object property. foreach(json_decode($apiResult) as $result){ echo $result->id; } but didn't work though. – Abu Shumon Nov 05 '15 at 10:08
  • The result is not an array but a simple object.. try it like I did to see if works – Mihai Matei Nov 05 '15 at 10:11
1

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
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149