doutou7549 2016-07-02 10:42
浏览 29
已采纳

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

Using Guzzle I am hooking into an API. The API will provide me with a valid JSON object that contains values I require. I have tried several methods to retrieve an array of values located within the response but at this point can only get one per request via the number of the row:

Here is my current code:

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

In my return dd($unique[0]->ean); I am receiving only one EAN value (via the number), so it will look like this;

"012345678910"

When I try to call it using return dd($unique->ean); I receive an error:

Laravel response

Bascially, what I need to do is get all the rows, not just one. so the request would be something like (for example purposes) return dd($unique[all]->ean); but I am not sure how to approach this?

Any help would be greatly appreciated.

Here is my response using just dd($unique);:

json

  • 写回答

1条回答 默认 最新

  • duanguochi6194 2016-07-02 11:06
    关注

    What result do you exactly wanna get?

    You could use "reduce" to get a single value from your collection.

    Or, if you just want to get a list of "ean"'s, use "map" and return only the ean for every row:

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

    There doesn't seem to be an "extract" method, but this should also work:

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

    For reference, here are all the collection methods:

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探