普通网友 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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line