-2

I'm calling a REST/JSON api from an php page. This is an sample successful JSON response:

{
   "code": 0,
   "message": "",
   "objects":
   {
      "UserRequest::123":
      {
         "code": 0,
         "message": "created",
         "class": "UserRequest",
         "key": 29,
         "fields":
         {
            "id": 29,
            "friendlyname": "R-000029"
         }
      }
   }
}

I just want to echo the id value in the page, but I can't get it to work. I have tried to json_decode the response

$decoded_response = json_decode($response, true);

and if I print_r the decoded response, it will look something like this:

Array ( [objects] => Array ( [UserRequest::17282] => Array ( [code] => 0 [message] => created [class] => UserRequest [key] => 17282 [fields] => Array ( [id] => 17282 ) ) ) [code] => 0 [message] => )
Fredrik
  • 7
  • 2
  • You can just go through your array and retrieve the id. Like this: `$decoded_response['objects']['UserRequest::17282']['fields']['id']` – Abbas Akhundov Jan 20 '21 at 15:40
  • Does this answer your question? [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – El_Vanja Jan 20 '21 at 15:44
  • Read about [accessing values in PHP arrays using square brackets](https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing). – axiac Jan 20 '21 at 15:50

2 Answers2

1

You can get the nested id by following the deep elements this way,

echo $decoded_response['objects']['UserRequest::123']['fields']['id'];

DEMO: https://3v4l.org/nUtUe

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

Managed to solve it like this:

foreach( $decoded_response['objects'] as $k=>$v) {
    if ( isset($v['key']) ) {
      echo 'Ticket created: ', $v['fields']['friendlyname'], "\r\n";
    }
}
Fredrik
  • 7
  • 2