PHP自动分页循环

时间:2019-03-28 11:35:32

标签: php

我有以下PHP代码和函数,可使用它们调用API url,并使用json_decode将数据作为数组返回。问题在于返回的数据是分页的。因此,有了页面的结果,我得到了一个名为nextPageID的数组键。因此,当我使用函数进行调用时,我只能从第一页获取第一组数据。有没有办法让我循环执行该函数,直到不再定义nextPageID参数?

$getData = getData("https://api.url/api?key=xyz");
$next_pageid = $getData['nextPageID'];

echo "<pre>";
print_r($getData);
echo "</pre>";


function getData($url){
    $json = file_get_contents($url);
    return json_decode($json,true);
}

1 个答案:

答案 0 :(得分:0)

您需要使用递归-函数中的调用函数。例如:

$api_url = "https://api.url/api?key=xyz";
function getData($api){
    $json = file_get_contents($api);
    $array = json_decode($json);
    //This is ok ONLY if on last page nextPageID = null and for get next page you need to use parametr nextPageID in GET
    if(isset($array['nextPageID']) && $array['nextPageID'] !== null){
        $array .= array_merge($array,(getData($api."&nextPageID=".$array['nextPageID']));
    }
    return $array;
}
print_r (getData($api_url));