从 JSON 响应中检索所有数字行

Retrieving all number row from JSON response

我正在使用 Guzzle 连接到 API。 API 将为我提供一个有效的 JSON 对象,其中包含我需要的值。我已经尝试了几种方法来检索位于响应中的一组值,但此时只能通过行号为每个请求获取一个值:

这是我当前的代码:

public function index () {
    //$value = "07332927917462,07332927917455";
    $client = new Client();
    $response = $client->get('https://example.com/xxx', 
                             [ 'query' => [
                             'secret' => '2acbefghijklmnop',
                             'created' => '2016-01-01']]);

    $data = json_decode($response->getBody()->getContents());
    $array = $data->products;
    $collect = collect($array);
    $unique = $collect->unique('ean');
    $unique->values()->all();


    return dd($unique[0]->ean);
  }

在我的 return dd($unique[0]->ean); 中,我只收到一个 EAN 值(通过数字),所以它看起来像这样;

"012345678910"

当我尝试使用 return dd($unique->ean); 调用它时,我收到一个错误:

Laravel response

基本上,我需要做的是获取所有行,而不仅仅是一行。所以请求会是这样的(出于示例目的)return dd($unique[all]->ean); 但我不确定如何处理这个?

如有任何帮助,我们将不胜感激。

这是我的回复 dd($unique);:

json

你到底想得到什么结果?

您可以使用 "reduce" 从您的集合中获取单个值。

或者,如果您只想获取 "ean" 的列表,请仅使用 "map" 和 return 每行的 ean:

$eans = $unique->map(function($item){
    return $item->ean;
})

似乎没有 "extract" 方法,但这应该也有效:

$eans = $unique->keyBy('ean')->keys();

仅供参考,收集方法如下:

https://laravel.com/docs/5.2/collections#method-keyby