Reputation: 23
I am using php/Laravel and i have a response from an API that returns the following format in my controller:
[
{
"id": "474",
"room_id": "14",
"user_id": "20",
"name": "121001.webm",
"fname": "",
"status": "0",
"date_recorded": "October 17 2018 07:18:51",
"size": "396135",
"is_public": "0",
"allow_download": "0",
"privatekey": "",
"duration": "0",
"record_path": "https:example/url/test.mp4",
"record_url": "https:example/url/test.mp4"
}
]
I believe this is an array inside of the array is the json object i want the data from, so for example I want the record id. I have used these solutions with no luck :
$response->record_url;
$response[0]->record_url;
also tried to encode or decode the $response
Any help would be greatly appreciated
Upvotes: 1
Views: 959
Reputation: 61
Please refer the below program and respective output:
$json = '[
{
"id": "474",
"room_id": "14",
"user_id": "20",
"name": "121001.webm",
"fname": "",
"status": "0",
"date_recorded": "October 17 2018 07:18:51",
"size": "396135",
"is_public": "0",
"allow_download": "0",
"privatekey": "",
"duration": "0",
"record_path": "https:example/url/test.mp4",
"record_url": "https:example/url/test.mp4"
}
]';
$array1 = json_decode($json, false);
echo $array1[0]->id //This will print the value of id which is 474.
$array2 = json_decode($json, true);
echo $array2[0]['id'] // This will also print th evalue of id which is 474.
The second parameter of the function json_decode is boolean when TRUE, returned objects will be converted into associative arrays.
Thanks
Upvotes: 0
Reputation: 15696
In JSON string, you have and array with one element being an object.
Now, depending on how you're decoding it, you'll get in PHP and array with stdClass
object, or array with associative array inside.
//this will return array with stdClass object
$data = json_decode($json);
echo $data[0]->record_url;
//this will return array with associative array
$data = json_decode($json, true);
echo $data[0]['record_url'];
Working code: https://3v4l.org/TJNQ1
Upvotes: 6