So I am fetching data from an URL which is in JSON Format Like this below.

[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
  "street": "Kulas Light",
  "suite": "Apt. 556",
  "city": "Gwenborough",
  "zipcode": "92998-3874",
  "geo": {
    "lat": "-37.3159",
    "lng": "81.1496"
  }
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
  "name": "Romaguera-Crona",
  "catchPhrase": "Multi-layered client-server neural-net",
  "bs": "harness real-time e-markets"
}
},
// And So on upto 10 id places.

Now what I want is to Fetch the data in my site using the cURL php .

My php Code looks like this :

$url = "https://jsonplaceholder.typicode.com/users" ;

$ch = curl_init() ;
curl_setopt($ch, CURLOPT_URL, $url) ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch) ;

$id = 1;
$data = json_decode($result) ;
foreach ($data as $mydata) {
  if ($mydata["id"] == $id) {
 echo $mydata["address"]["street3"] ;
 break ;
}
}

But What I am getting is an error :

Cannot use object of type stdClass as array

1 Answers

0
M.Hemant On Best Solutions

second param When TRUE, returned objects will be converted into associative arrays.

$data = json_decode($result,true) ;
foreach ($data as $mydata) {
  if ($mydata["id"] == $id) {
      echo $mydata["address"]["street"] ;//changes `street3` is not there
      break ;
  }
}

By default json_decode will return you objects and if you want to use [] syntax you need associative array and only for that you need to pass second param true please refer this json_decode for further queries