【问题标题】:PHP API offset PaginationPHP API 偏移分页
【发布时间】:2021-02-27 00:59:00
【问题描述】:

我有以下代码,但我不确定如何循环和偏移记录以使用相同的函数循环获取接下来的 20 条记录。

第一次调用时,gameid 为零,第二次调用时,gameid 为 21。

$result = new ArrayObject();

  
$count = 0;
foreach($response as &$game) {
    
    $game  = get_object_vars($game);
         
    if ($game['gameType'] == $gametype )
    {   
        $result->append(array($game['gameName'], $game['gameType']));
        if ($count == $gameid+19) break;
        $count ++ ;
        
    }       
    
}

谢谢

【问题讨论】:

  • 这将取决于您计划在循环完成后对$response 做什么。您正在填充$result,这对我来说表明您的$response 最好保持原样,但您正在转换它的每个元素。为什么?如果你只需要分页,那么你可以使用foreach(array_slice($response, $offset, $limit) as $game) {之类的东西。
  • 谢谢@RoAchterberg,但我不能使用它,因为我想按游戏类型 $game['gameType'] == $gametype
  • 那么为什么不先在这种情况下过滤$response,以便您只对特定游戏类型元素的数组进行分页呢?

标签: php arrays json pagination


【解决方案1】:

我认为你应该使用页面大小和页面索引的概念。

在您的情况下,您似乎希望页面大小为 20。使用 gameid 发送第二个请求意味着您希望页面大小为 20,页面索引为 1(而不是 0)。

所以考虑这样的代码:

$count = 0;
$pageSize = 20; // this can be const or come as param
$pageIndex = 0; // this should be as params
foreach($response as &$game) {

    $game  = get_object_vars($game);
     
    if ($game['gameType'] == $gametype ) {
        $count++ ;
        if ($count > ($pageSize * $pageIndex))
            $result->append(array($game['gameName'], $game['gameType']));
        // if you over the request chunk break
        if ($count > ($pageSize * ($pageIndex + 1)) break; 
        
    
    }       

}

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 2019-09-08
    • 2016-03-16
    • 2013-09-17
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2013-08-24
    • 2012-04-19
    相关资源
    最近更新 更多