普通网友 2018-03-15 09:41
浏览 48
已采纳

一个数组中有两个单独的API调用值

Situation

I have two API calls, one to get all the devices and one to get all the groups. What I would like to accomplish is to have one call that would fetch the groups with its devices.

This is the function to get the devices

public function getAll($environment, $options)
{
    // Get group ids from database, used for pairing groups with environments
    $groups = Device::where('source_id', $options['deviceSourceId'])->get();
    $groupIds = [];
    foreach ($groups as $group) {
        $groupIds[] = $group['group_id'];
    }

    // Parameters
    $apiparams = [
        'headers' => $this->getHeaders($environment)
    ];

    $devices = [];

    foreach($groupIds as $groupId)
    {
        $responseAPI = $this->getClient()->request('GET', 'devices?groupid=' . $groupId, $apiparams);
        $responseAPI = json_decode($responseAPI->getBody()->getContents(), true);
        $devices[] = $responseAPI['devices'];
    }

    return $devices;
}

This is the function to get the groups

public function getGroups($environment, $options)
{
    // Get group ids from database, used for pairing groups with environments
    $groups = Device::where('source_id', $options['deviceSourceId'])->get();
    $groupIds = [];
    foreach ($groups as $group) {
        $groupIds[] = $group['group_id'];
    }

    // Parameters
    $apiparams = [
        'headers' => $this->getHeaders($environment)
    ];

    $groups2 = [];

    foreach($groupIds as $groupId)
    {
        $responseAPI = $this->getClient()->request('GET', 'groups/' . $groupId, $apiparams);
        $responseAPI = json_decode($responseAPI->getBody()->getContents(), true);

        $groups2[] = $responseAPI;
    }
    return $groups2;
}

Current response

This is the response I get from these.

// Device response
[
    {
        "remotecontrol_id": "r5674567"
        "device_id": "d871212",
        "alias": "PC-01",
        "groupid": "g9873491",
        "online_state": "Online",
        "assigned_to": false
    },
    {
        "remotecontrol_id": "r8370129"
        "device_id": "d091231",
        "alias": "PC-02",
        "groupid": "g9873491",
        "online_state": "Offline",
        "assigned_to": false
    }
]

// Group response
{
    "id": "g9873491"
    "name": "companyname",
    "permissions": "owned"
}

Needed response

The response I would like to get is:

[{id: "g9873491",
  name: "companyname",
  devices: [{device_id: "d871212",
             alias: "PC-01",
             online_state: "Online"},
            {device_id: "d091231",
             alias: "PC-02",
             online_state: "Offline"}
            }],
}]

How would I need to do this?

Sevavietl edit

public function getAll($environment, $options)
{
    // Get group ids from database, used for pairing groups with environments
    $groups = Device::where('source_id', $options['deviceSourceId'])->get();
    $groupIds = [];
    foreach ($groups as $group) {
        $groupIds[] = $group['group_id'];
    }

    // Parameters
    $apiparams = [
        'headers' => $this->getHeaders($environment)
    ];

    foreach($groupIds as $groupId)
    {

        $responseAPI1 = $this->getClient()->request('GET', 'groups/' . $groupId, $apiparams);
        $responseAPI2 = $this->getClient()->request('GET', 'devices?groupid=' . $groupId, $apiparams);

        $groups2 = json_decode($responseAPI1->getBody()->getContents(), true);
        $devices = json_decode($responseAPI2->getBody()->getContents(), true);

        $result = array_values(array_reduce(
            $devices,
            function ($carry, $device) {
                if (isset($carry[$device['groupid']])) { // Undefined index: groupid
                    // Add device to group.
                    $carry[$device['groupid']]['devices'][] = [
                        'device_id' => $device['device_id'],
                        'alias' => $device['alias'],
                        'online_state' => $device['online_state']
                    ];
                }

                return $carry;
            },
            // Reindex groups by id.
            array_column($groups2, null, 'id')
        ));
    }

    return $result;
}
  • 写回答

1条回答 默认 最新

  • douhuang7263 2018-03-16 07:16
    关注

    If you don't have control over the API, I guess you cannot reduce the number of calls, as you have only calls defined by the API itself. So one solution would be to prepare the response in needed format yourself. You can do the following:

    $devices = json_decode($devices, true);
    $groups = json_decode($groups, true);
    
    $result = array_values(array_reduce(
        $devices,
        function ($carry, $device) {
            if (isset($carry[$device['groupid']])) {
                // Add device to group.
                $carry[$device['groupid']]['devices'][] = [
                    'device_id' => $device['device_id'],
                    'alias' => $device['alias'],
                    'online_state' => $device['online_state']
                ];
            }
    
            return $carry;
        },
        // Reindex groups by id.
        array_column($groups, null, 'id')
    ));
    

    Here is the demo.

    As you are using Laravel, another approach would be to take advantage of Laravel Collections. But in this particular situation, I guess, unless you are the collections guru (and read "Refactoring to Collections" from cover to cover:)) the plain PHP array functions is easier to understand and work with.

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

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: