Php 按id获取并组合多个json请求

Php 按id获取并组合多个json请求,php,json,Php,Json,首先,我有两个API URL: 它输出版本列表和哈希作为ID [ { "versions": [ { "version": "1.0", "hash": "15ac8f7dfcef3f3b9b3b5a48a7bee327", }, { "version": "1.1", "h

首先,我有两个API URL: 它输出版本列表和哈希作为ID

[
    {
        "versions": [
            {
                "version": "1.0",
                "hash": "15ac8f7dfcef3f3b9b3b5a48a7bee327",
            },
            {
                "version": "1.1",
                "hash": "5990bf1b3f11225d970c5d266e77e641",
            }
        ]
    }
]
然后通过POST请求,POST使用哈希来获取版本详细信息。换句话说,当GET:/api/version/15AC8F7DFCEF3B9B3B5A48A7BEE327中请求时,这是输出:

[
    {
        "id": "1",
        "name": "Example",
        "type": "version",
        "version": "1.0",
        "file_name": "testfile.txt",
        "hash": "15ac8f7dfcef3f3b9b3b5a48a7bee327",
    }
]
我试图做的是创建一个foreach循环,从api/list URL读取哈希值,获取所有版本详细信息,并将它们组合成一个数组,这样当编码回json时,输出将显示:

[
    {
        "id": "1",
        "name": "Example1",
        "type": "version",
        "version": "1.0",
        "file_name": "testfile1.txt",
        "hash": "15ac8f7dfcef3f3b9b3b5a48a7bee327",
    },
    {
        "id": "2",
        "name": "Example2",
        "type": "version",
        "version": "1.1",
        "file_name": "testfile2.txt",
        "hash": "5990bf1b3f11225d970c5d266e77e641",
    }
]
我不完全确定如何使用foreach循环来实现这一点,因为我正在使用一个json请求中的值来调用一个API并获取另一个API。

我将使用库来获取列表,然后解码响应体,对哈希进行迭代,为每个请求生成一个新的请求并附加其结果

class ApiHashGet
{
    public function fetchAll(string $api) : string
    {
        $client = new \GuzzleHttp\Client;

        $response = $client->request('GET', "$api/list");

        $list = json_decode($response->getBody(), $array = true)[0]['versions'];

        foreach ($list as $item) {
            $response = $client->request('GET', "$api/version/$item[hash]");
            $result []= json_decode($response->getBody(), $array = true)[0];
        }

        return json_encode($result ?? []);
    }
}
然后通过传递API基URL来调用它

echo (new ApiHashGet)->fetchAll('https://example.com/api');
我继续为您创建了一个基于travis ci的单元测试:

我将使用库获取列表,然后解码响应体,迭代哈希,为每个哈希生成新的请求,并附加其结果

class ApiHashGet
{
    public function fetchAll(string $api) : string
    {
        $client = new \GuzzleHttp\Client;

        $response = $client->request('GET', "$api/list");

        $list = json_decode($response->getBody(), $array = true)[0]['versions'];

        foreach ($list as $item) {
            $response = $client->request('GET', "$api/version/$item[hash]");
            $result []= json_decode($response->getBody(), $array = true)[0];
        }

        return json_encode($result ?? []);
    }
}
然后通过传递API基URL来调用它

echo (new ApiHashGet)->fetchAll('https://example.com/api');
我继续为您创建了一个基于travis ci的单元测试:


您是如何获得这些json响应的?通过curl或ajax?如何获得这些json响应?通过curl还是ajax?