代码之家  ›  专栏  ›  技术社区  ›  Urs

php:total的某些块循环,然后rest

  •  0
  • Urs  · 技术社区  · 7 年前

    我不确定我做的是否正确:

    我有很多东西,比如说624件。我想做一个循环,发送7个请求,前6个超过100个项目,最后一个超过24个。

    所以我做了一些数学运算,找出我要经历多少个循环。

        // this is the total number of items
        $total = $result['total_items'];
        // if we split the total into such chunks
        $chunksize = 50;
        // we will get a rest of so many items
        $rest = $total % $chunksize;
        // so including the query for the rest, we will have to repeat the query so many times
        $queries_no = (($total-$rest)/$chunksize)+1;
    

    上面的感觉有点笨拙。这条路对吗?

    PS:之后,我可以重复查询必要的次数。

        // prep loop
        $i = 0;
        $requested = 0;
        $subscribers = [];
    
        while ($i <= $queries_no){
            // last item
            if($i == $queries_no){
                $chunksize = $rest;
            }
            $result = $this->monkeyApp->get('lists/'.$list_id.'/members?offset='.$requested.'&count='.$chunksize);
            $subscribers = array_merge($subscribers,$result['members']);
            $requested = $requested + $chunksize;
            $i++;
        }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   user1597430    7 年前
    $subscribers = [];
    
    for ($count = $chunksize, $offset = 0; $offset < $total; $offset += $chunksize)
    {
        if ($offset + $chunksize > $total)
        {
            $count = $total % $chunksize;
        }
    
        $result = $this->monkeyApp->get("lists/$list_id/members?offset=$offset&count=$count");
    
        $subscribers = array_merge($subscribers, $result['members']);
    }
    
    推荐文章