dongyu4908 2017-07-10 09:17
浏览 333
已采纳

如何使用Guzzle和Laravel从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);

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!

  • 写回答

3条回答 默认 最新

  • dotn30471 2017-07-10 09:21
    关注

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

报告相同问题?

悬赏问题

  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥15 MATLAB数据处理插值
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的
  • ¥15 硬件IIC从模式的数据发送,中断数据的接收,不能用HAL库(按照时序图)