代码之家  ›  专栏  ›  技术社区  ›  Robert Andrews

如何进行分页的循环函数调用?

  •  1
  • Robert Andrews  · 技术社区  · 7 年前

    Airtable API

    我写了一个函数, get_airtable_records ,通过 curl $article_urls .

    唯一的问题是,Airtable将返回的结果限制为最多100条记录的“页面”,而我的数据包含的内容不止这些。API接受参数 maxRecords 和 pageSize 但更重要的是, 页面大小

    Airtable还返回另一个Json值, offset ,在这种情况下用于分页。这个 是打算用作输入参数的记录ID(也称为 ). 你可以用它来表示 启动 记录在随后的附加API调用中。我明白这一点 .

    换言之,我们应该始终从头开始,在没有 抵消 那么如果 值出现在返回的结果中,我们应该再次遍历-直到 抵消

      // Make get request, store result in array
      $articles = get_airtable_records($offset); // $offset won't exist at the start
    
      // Prepare Article URLs list as an array
      if (!isset($article_urls)) {
         $article_urls = array();
      }
    
      // For each URL found in Airtable
      foreach($articles['records'] as $record){
         $url = $record['fields']['Published URL'];
         // Add to our array list
         if (!empty($url)) {
            array_push($article_urls, $url);
         }
      }
    
      // URL list after first pass:
      echo '<pre>';
      print_r($article_urls);
      echo '</pre>';
      // May hit a max of 100
    
      // echo 'Offset: ' . $articles['offset'];
      // Value like "itrJYSLx0RfslI80f/recEu6TiPTPCSDxg5" may exist.
      // If so, go back to start, do get_airtable_records($offset) again and array_push
      // Until, once more there is no "offset" value at end
    

    我推测某种 while 循环将是有用的?

    有几件事是真的。。。

    • 抵消 需要传递的值,因为它从记录0开始。
    • 但这一过程和随后的过程可能会产生 抵消
    • 最终的 抵消
    1 回复  |  直到 7 年前
        1
  •  1
  •   Robert Andrews    7 年前

    @anthony's answer to a similar question here ,我似乎有一些工作代码。。。

      // Prepare Article URLs list as an array
      $article_urls = array();
    
      // Call Airtable records in pages of 100 max
      do {
    
            // Offset is either inherited from last page's results, or is nothing
            $offset = $articles['offset'] ?: "";
    
            // Make get request, store result in array
            $articles = get_airtable_records($offset);
    
            // For each URL found in Airtable
            foreach($articles['records'] as $record){
               $url = $record['fields']['Published url'];
               // Add to our array list
               if (!empty($url)) {
                  array_push($article_urls, $url);
               }
            }
    
      } while(!empty($articles['offset'])); // If there's an offset value (ie. starting record of next page), do again
    
      // Output URL list for check
      echo '<pre>';
      print_r($article_urls);
      echo '</pre>';
    

    do while 环 在开始时,设置 offset

    我的 get_airtable_records 函数已限制是否存在 在API调用中,使用以下命令添加

      if (!empty($offset)) {
        $q_offset = '&offset='.$offset;
      }
    

    我已经测试了这个,它给了我所有137个结果,从两页到我的 $article_urls 大堆我没有用超过两页的结果来测试它。