2016-08-02 97 views
0

我試圖從幾個API請求中提取數據到一個數組中(用於顯示),並且API限制了我一次可以提取的記錄數量。不幸的是,我沒有足夠的客戶端購買來測試我的遞歸,所以我希望有人可以看看我的測試類,看看它是否可以工作。php基於api記錄計數響應的遞歸函數

這是我到目前爲止。請求方法需要參數$ service和$ page,然後根據有多少個'recsindb'遞增$ page。例如,如果recsindb = 50,那麼$ page應該增加5次,每組中有10條記錄。

這是我寫的代碼:我結束了創建數據庫和API服務,以模擬過程

$check = new testClass; 

// API services to loop through 
$services = array(
    "dns" => "domains/search.json", 
    "webservices" => "webservices/search.json", 
    "singledomainhostinglinuxus" => "singledomainhosting/linux/us/search.json", 
    "singledomainhostinglinuxuk" => "singledomainhosting/linux/uk/search.json" 
); 

// foreach service, assign a key to identify the data in the display 
foreach ($services as $key => $value) { 
    $data[$key] = $check->getData($value); 
} 

// Let's see what we got 
echo "<pre>" . print_r($data, TRUE) . "</pre>"; 

class testClass { 

    function getData($api) { 
     $fullurl = "https://myapipath/" . $api . "?" . $this->buildstring(); 
      $ch = curl_init(); 
      curl_setopt($ch, CURLOPT_HEADER, 0); 
      curl_setopt($ch, CURLOPT_URL, $fullurl); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
      $data = curl_exec($ch); 
      curl_close($ch); 
     return json_decode($data, true); 
    } 

    // Array key => value pairs 
    private $parts = array(); 

    public function add($key, $value) { 
     $this->parts[] = array(
      'key' => $key, 
      'value' => $value 
     ); 
    } 

    // Build the query string 
    public function buildstring($separator = '&', $equals = '=') { 
     $queryString = array(); 

     foreach ($this->parts as $part) { 
      $queryString[] = urlencode($part['key']) . $equals . urlencode($part['value']); 
     } 

     return implode($separator, $queryString); 
    } 

    // recursive function 
    public function request($service, $page) { 
     $count = 10; // 10 records is the minimum allowed to request 
     $this->add(array('no-of-records', $count)); 
     $this->add(array('page-no', $page)); 
     $data = $this->getData(array($service, TRUE)); 

     if ($data[0]['recsindb'] > $page * $count) { 
      $data = $this->request($service, $page + 1); 
     } 
     return $data; 
    } 
} 
+1

您應該創建一個代碼,它會生成必要的輸入,然後使用它來測試您的代碼。 –

+0

所以我應該建立自己的API來提出反對請求?我希望這會有點矯枉過正,贊成某人只是說「這不會起作用」或「這裏有更好的方式」。 –

+1

讓我們假設有人會這樣做。這只是一個意見,除非進行測試,所以不幸的是,除此之外別無選擇。 –

回答

0

。到目前爲止,這種請求方法與array_merge似乎是我正在尋找:

// recursive function 
public function request($service, $page) { 
    $count = 10; 
    $this->add('no-of-records', $count); 
    $this->add('page-no', $page); 
    $data = $this->getData($service); 

    if ($data['recsindb'] > $page * $count) { 
     $data = array_merge($data, $this->request($service, $page + 1)); 
    } 
    return $data; 
}