How to extract individual array values ​​from the JSON response using Guzzle and Laravel

advertisements

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!


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);