问题
I'm struggling to get data from JSON response. This is my code for getting the data:
$client = new Client;
$r = $client->get("http://my.api.com/get-campaign/" . $id . "?api_token=1235");
$apiResult = json_decode($r->getBody(), true);
dd($apiResult);
And I get something like this:
array:4 [
"campaign" => array:1 [
0 => array:3 [
"manufacturer" => "Sony"
"product" => "PlayStation 4"
"created_at" => "2015-07-04T00:00:00+00:00"
]
]
"media" => array:2 [
"video" => "https://my.domain.com/421156.mp4"
"images" => "https://my.domain.com/tv/thumbs/421156-1.jpg"
]
"statistics" => array:3 [
"runs" => 172
"firstseen_at" => "2015-07-04T19:06:41+00:00"
"lastseen_at" => "2015-07-09T12:04:13+00:00"
]
"broadcasts" => array:172 []
]
How can I get single values from this response? Let's say I want to display, or assign to another variable the value of "manufacturer"
and in another variable to store number of runs ("runs"
)?
For manufacturer I've tried to do something like this:
dd($apiResult["campaign"]->manufacturer);
But then error is shown - trying to get non-property object!
回答1:
You're mixing object access with array access.
$apiResult = json_decode($r->getBody(), true);
dd($apiResult["campaign"][0]["manufacturer"]);
or with objects
$apiResult = json_decode($r->getBody(), false);
dd($apiResult->campaign[0]->manufacturer);
回答2:
Looks like campaign is an array so you would need to do:
$apiResult["campaign"][0]->manufacturer
回答3:
If you want to play with object then use following:
$apiResult = json_decode($r->getBody());
dd($apiResult->campaign[0]->manufacturer);
or want an associative array
$apiResult = json_decode($r->getBody(), true);
dd($apiResult["campaign"][0]["manufacturer"]);
For more detail read documentation of json_decode
来源:https://stackoverflow.com/questions/45008152/how-to-extract-individual-array-values-from-json-response-using-guzzle-and-larav