0

I want to use decoded JSON data as php objects to be able to used as follows:

return $data->title 

however im running into a few errors. I am able to connect to the remote API url and get the requested data.

$api = 'https://remote.api.url/dataset/list'; $json = file_get_contents($api); $data = json_decode($json, true); dd($data); 

When i die and dump the data i see the following:

array:1 [▼ "data" => array:5 [▼ 0 => array:5 [▼ "id" => "qk4GtMb8" "title" => "SSA's palliative care has an mHealth deficit " "image" => "http://gstatic.acfee.org/akamaihd/i/52fdb957187" "published_at" => "2016-06-10 08:05:00" "created_at" => array:3 [▼ "date" => "2016-06-07 05:48:34.000000" "timezone_type" => 3 "timezone" => "UTC" ] ] 1 => array:5 [▶] 2 => array:5 [▶] 3 => array:5 [▶] 4 => array:5 [▶] ] ] 

But i am unable to use the recieved data in object form. return $data->title;

i am pretty new to JSON any help would be appreciated. Thanks in advance.

1 Answer 1

2

The second parameter of json_decode (which in your case is true) converts the objects to array. From official PHP docs: When TRUE, returned objects will be converted into associative arrays. So if you remove it you should be ok.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for this. it helped. my final question is i can only return 1 title. in the foreach i have echo $data[0]->title; which works but only returs one. how can i loop through each of them
@WesMurray why don't you loop all the $data instead of only the first one $data[0]?
please see here pastebin.com/4ig5H8t5 - but this code seems a bit messy. foreach within a foreach
@WesMurray if you have array of data that inside has another arrays I don't see another way to access them other than loop inside a loop.