-4

I've got basic array from my api:

{ "title": "offer title", "body": "offer body", 
"specialities": { "lang": "en", "id": "1", "icon": "0",
"name": "speciality name 1" }, "region": "region1" }

I want to get id value from request for my php variable lets say: $idVariable. How can I do it?

I tried something like:

$idVariable = $request->specialities[0]->id

but it seems not working. What is the right way?

Then how should I work with the arrays of object in this case:

{ "title": "offer title", "body": "offer body", 
"specialities": [
{ "lang": "en", "id": "1", "icon": "0", "name": "speciality name 1" },
 { "lang": "en", "id": "2", "icon": "0", "name": "speciality name 2" },
 { "lang": "en", "id": "2", "icon": "0", "name": "speciality name 3" },
 etc...], "region": "region1" }

To get id's of every object in specialities array? I know that it could be a duplicate question, but I ask for just a basic example.

I tried to use json decode like below:

json_decode($request->get('specialties'))->id

edit:

The almost-right way to do it is to decode json file first:

$data = json_decode($request);

and then get the right property from the array:

$id = $data['specialities'][0]['id'];

the problem now is that id is a string not an integer and by simply using:

$int_id = intval($id)

I've got $int_id = 0 instead of 1,2,3 etc

gileneusz
  • 1,435
  • 8
  • 30
  • 51

1 Answers1

0

You are getting a response from API in JSON you should use json_decode() and then use the data. Try this code.

$json = '{ "title": "offer title", "body": "offer body", 
"specialities": { "lang": "en", "id": "1", "icon": "0",
"name": "speciality name 1" }, "region": "region1" }';

$data = json_decode($json);
echo $data->specialities->id;
TIGER
  • 2,864
  • 5
  • 35
  • 45
  • 1
    this should work but I've got `"message": "Trying to get property of non-object",` my code is: `$data = json_decode($request);` `$offer->specialities()->sync($data->specialities->id, false);` – gileneusz Apr 08 '18 at 17:58
  • 1
    might be your response data has not a valid data? check your data before trying to get property like `if ($data->specialities) { // Now get property if the object is available}` – TIGER Apr 08 '18 at 18:01
  • 1
    got the same error within if statement – gileneusz Apr 08 '18 at 18:04
  • 1
    @gileneusz might be your object does not have the property. Please check your response data. – TIGER Apr 08 '18 at 18:07