分页的 api 请求,如何知道是否还有其他页面? [英] paginated api request, how to know if there is another page?

查看:24
本文介绍了分页的 api 请求,如何知道是否还有其他页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个使用 3rd 方 API 的 PHP 类.API 有一个具有此请求 URL 结构的方法:

I am creating a PHP class that use a 3rd party API. The API has a method with this request URL structure:

https://api.domain.com/path/sales?page=x

其中x"是页码.

每页返回 50 个销售,我需要为每个用户返回未定义数量的页面(取决于用户销售)并存储每次销售的一些数据.

Each page return 50 sales and I need to return an undefined number of pages for each user (depending on the user sales) and store some data from each sale.

我已经创建了一些从 URL 获取数据、解码并使用所需数据创建新数组的方法,但仅限于第一个页面请求.

I have already created some methods that get the data from the URL, decode and create a new array with the desired data, but only with the first page request.

现在我想创建一个方法来检查是否有另一个页面,如果有,获取它并再次检查

Now I want to create a method that check if is there another page, and if there is, get it and make the check again

如何查看是否有其他页面?以及如何创建一个循环以获取另一个页面(如果有)?

我已经有了这段代码,但它会造成无限循环.

I have already this code, but it create an infinite loop.

require('classes/class.example_api.php');
$my_class = new Example_API;
$page = 1;
$sales_url = $my_class->sales_url( $page );
$url = $my_class->get_data($sales_url);

while ( !empty($url) ) {
    $page++;
    $sales_url = $my_class->sales_url( $page );
    $url = $my_class->get_data($sales_url);
}

我不使用 CURL,我使用 file_get_content.当我请求超出范围的页面时,我得到以下结果:

I don't use CURL, I use file_get_content. When I request a page out of range, I get this result:

string(2) "[]"

json_decode 之后的另一个:

array(0) { }

推荐答案

根据您的输入,在 while 循环中,您更改 $url(实际上保存 API 调用返回的数据)并检查是否为空,如果我是对的.

From your input, in the while loop, you change the $url (which actually holds the data return by the API call) and this is checked for emptiness, if I'm correct.

$url = $my_class->get_data($sales_url);

如果以上只是原始响应(因此在页面超出范围的情况下是字符串[]"),它将永远不会将 empty("[]") 变为 true.所以我的猜测是 get_data 的返回值是这个字符串,而它应该是实际的数组/json,即使结果为空(即我怀疑一旦你收集了数据,例如在循环之外,你就执行了 json_decode).

If the above is just the original response (so in case of page out of range a string "[]"), it will never get empty("[]") to true. So my guess is that the return value from get_data is this string, while it should be the actual array/json even if the result is empty (ie I suspect that you perform the json_decode once you have collected the data e.g. outside the loop).

如果是这种情况,我的建议是在循环中检查[]"(例如 while ($url !== "[]"))或在循环内解码响应数据($url= json_decode($url)).

If this is the case, my suggestion would be to either check for "[]" in the loop (e.g. while ($url !== "[]")) or within the loop decode the response data ($url = json_decode($url)).

这篇关于分页的 api 请求,如何知道是否还有其他页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆