首页 > 解决方案 > 如何通过 id laravel 过滤 json api 响应

问题描述

我正在调用端点以获取返回大量数据的数据。我需要将我需要的那些划分到我自己的类别中。基本上,当我拨打电话时,我会收到此示例响应。

{
    "status": "success",
    "message": "bill categories retrieval successful",
    "data": [{
        "id": 1,
        "biller_code": "BIL099",
        "name": "MTN NIgeria",
        "default_commission": 0.03,
        "date_added": "2018-07-03T00:00:00Z",
        "country": "NG",
        "is_airtime": true,
        "biller_name": "AIRTIME",
        "item_code": "AT099",
        "short_name": "MTN",
        "fee": 0,
        "commission_on_fee": false,
        "label_name": "Mobile Number",
        "amount": 0
    }, {
        "id": 2,
        "biller_code": "BIL099",
        "name": "GLO Nigeria",
        "default_commission": 0.03,
        "date_added": "2018-07-03T00:00:00Z",
        "country": "NG",
        "is_airtime": true,
        "biller_name": "AIRTIME",
        "item_code": "AT099",
        "short_name": "GLO",
        "fee": 0,
        "commission_on_fee": false,
        "label_name": "Mobile Number",
        "amount": 0
    }, 
... //on and on
}

在我的代码中,我有这个来过滤它,但它返回空......

public function billPower()
{
    $response = Http::withToken('FLWSECK_******-X')->get('https://baseUrl/v3/bill-categories', [

    ]);
    $collection = collect($response->json());
    $filtered = $collection->whereIn('id', [1, 2, 3, 4]);
    return $filtered->all();
}

我怎样才能在laravel中做到这一点?

标签: phplaravel

解决方案


你需要做:

$collection = collect($response->json()['data']);

那么你的过滤器应该可以工作

$filtered = $collection->whereIn('id', [1, 2, 3, 4]);

推荐阅读