2017-06-15 34 views
1

首先,我有兩個API URL: http://example.com/api/list它輸出一個版本列表和散列作爲ID。獲取併合並多個json請求,編號爲

[ 
    { 
     "versions": [ 
      { 
       "version": "1.0", 
       "hash": "15ac8f7dfcef3f3b9b3b5a48a7bee327", 
      }, 
      { 
       "version": "1.1", 
       "hash": "5990bf1b3f11225d970c5d266e77e641", 
      } 
     ] 
    } 
] 

然後http://example.com/api/version通過POST請求,它使用哈希來提取版本細節。換句話說,當GET請求:/ API /版本/ 15ac8f7dfcef3f3b9b3b5a48a7bee327這是輸出:

[ 
    { 
     "id": "1", 
     "name": "Example", 
     "type": "version", 
     "version": "1.0", 
     "file_name": "testfile.txt", 
     "hash": "15ac8f7dfcef3f3b9b3b5a48a7bee327", 
    } 
] 

我試圖做的是做一個foreach循環來讀取API/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並獲得另一個。

+0

你是如何獲得這些JSON響應?通過捲曲或ajax? –

回答

0

我會使用Guzzle HTTP client庫來獲取列表,然後解碼響應主體,迭代散列,爲每個請求創建一個新請求並追加結果。

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

我繼續爲您創建一個demo Github repository與建立在特拉維斯-CI單元測試:

https://travis-ci.org/scratchers/apihashget/builds/243475865