我有以下PHP代码和函数,我用它们调用API url并使用json_decode将数据作为数组返回。问题是返回的数据是分页的。因此,对于页面的结果,我得到了一个名为 nextPageID 的数组键。因此,当我使用该函数进行调用时,我只能从第一页获取第一组数据。有没有办法让我循环函数直到不再定义下一个PageID参数?
$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);
}
你需要使用递归 - 在函数中调用函数。例如:
$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));