如何使用Guzzle和Laravel从JSON响应中提取单个数组值 [英] How to extract individual array values from JSON response using Guzzle and Laravel

查看:476
本文介绍了如何使用Guzzle和Laravel从JSON响应中提取单个数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力从JSON响应中获取数据.这是我获取数据的代码:

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

我得到这样的东西:

    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 []
]

如何从此响应中获取单个值?假设我要显示或将"manufacturer"的值分配给另一个变量,并在另一个变量中存储运行次数("runs")?

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

或带有对象

$apiResult = json_decode($r->getBody(), false);
dd($apiResult->campaign[0]->manufacturer);

这篇关于如何使用Guzzle和Laravel从JSON响应中提取单个数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆