php递归函数基于api记录计数响应


php recursive function based on api record count response

我试图将多个API请求中的数据拉入单个数组(用于显示),而API限制了我一次可以拉取的记录数量。不幸的是,我没有足够的客户端购买来测试我的递归,所以我希望有人能看看我的测试类,看看它是否应该工作。

这是我迄今为止所拥有的。request方法采用参数$service和$page,然后根据"recsindb"的数量增加$page。例如,如果recsindb=50,那么$page应该增加5倍,每组中有10条记录。

这是我写的代码:

$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;
    }
}

我最终创建了一个数据库和API服务来模拟流程。到目前为止,这个带有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;
}