drfu29983 2019-06-23 13:24
浏览 162

PHP - 如果我只能在一次调用中获取100个项目,是否有一种循环遍历JSON文件中所有元素的方法?

I need to display all the elements/objects of a JSON file. I can currently only call an endpoint that takes an offset (starting index) and limit. The maximum number of elements you could get is 100 (the limit) at one call. I was wondering how could I get all of the elements of a JSON file and store them in an array without knowing how many elements there are in the JSON file.

Initially I tried to save the first 500 elements in an array. The problem with that was that the output size of that array was 5 and not 500 because the getElements endpoint returns a list of 100 elements, so what the array actually stored was 100 elements at each index. So for example json_array[0] contains the first 100 elements, json_array[2] contains the next 100 elements etc.

$offset = 0;
$limit = 100;
$json_array = array();

while($offset < 500)
{
array_push($json_array,getElements($token,"api/Elements?offset=".$offset."&limit=".$limit));
$offset+=100;
}

echo count($json_array)

I am expecting to find a way to loop through the entire json file without knowing the number of elements that the file has. My final expectation is to find a way to display the number of all of these elements. Thank you!

  • 写回答

1条回答 默认 最新

  • dqgxazo4483 2019-06-23 15:21
    关注

    I work with a similar API - there is a per_page option and a page option.

    Fortunately, the API I'm hitting is set up to return everything with no error if there are less results than the per_page value, so what I do is simply loop while I fetched 100 records.

    Something like:

    $fetched=100;
    $page=0;
    $per_page=100;
    $total_result=array();
    while($fetched==100){
    
      $res=json_decode(file_get_contents($API_URL."?offset=".($page*$per_page));
    
      $fetched=count($res);
    
      // add res to big result set
      for($i=0;$i<$fetched;$i++){
         $total_result[]=$res[$i];
      }
    
      $page++;   
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?