【问题标题】:Pagination for foreach loopforeach 循环的分页
【发布时间】:2015-11-28 13:05:00
【问题描述】:

我目前在“汽车类”中有一个显示汽车的方法:

        static function getCars(){
        $autos = DB::query("SELECT * FROM automoviles");
        $retorno = array();
        foreach($autos as $a){
            $automovil = automovil::fromDB($a->marca, $a->modelo, $a->version, $a->year, $a->usuario_id, $a->kilometraje, $a->info, 
                        $a->hits, $a->cilindrada, $a->estado, $a->color, $a->categoria, $a->precio, $a->idAutomovil);
            array_push($retorno, $automovil);
        }
        return $retorno;
    }

在我的 index.php 中,我调用了该函数

foreach(car::getCars() as $a){ 

这允许我以这种方式显示信息(当然在 foreach 中我有一个巨大的代码,其中包含我将显示的详细信息。

有没有办法实现对那个东西的分页,这样我每页可以处理 8 辆汽车,而不是在同一页面上显示所有汽车?

【问题讨论】:

  • 你在使用任何框架吗?我不确定 DB::select 是什么?

标签: php pagination


【解决方案1】:

您可以在函数上添加$limit$page 参数,以便它只返回从$limit * $page 开始的最多$limit 数量的项目@(或将其称为@987654326 @)。您还需要添加一个函数来获取 automoviles 表的总行数。

static function getCars($page = 0, $limit = 8){
    $offset = $limit * max(0, $page - 1);

    //replace this with prepared statement
    $autos = DB::query("SELECT * FROM automoviles LIMIT $offset, $limit"); 

    $retorno = array();

    foreach($autos as $a){
        $automovil = automovil::fromDB($a->marca, $a->modelo, $a->version, $a->year, $a->usuario_id, $a->kilometraje, $a->info, 
                    $a->hits, $a->cilindrada, $a->estado, $a->color, $a->categoria, $a->precio, $a->idAutomovil);
        array_push($retorno, $automovil);
    }
    return $retorno;
}

static function getTotal() 
{
   //query to get total number of rows in automoviles table
}

在你的 index.php 中这样做:

foreach(car::getCars((isset($_GET['page']) ? $_GET['page'] : 1)) as $a){ 
   ...
}

并添加分页链接。

$total = car::getTotal();

if($total > 8) {
    for($i = 1; $i <= intval(ceil(1.0 * $total / $limit)); $i++) {
        echo '<a href="index.php?page=' . $i . '">' . $i . '</a>;
    }
}

【讨论】:

    猜你喜欢
    • 2012-08-06
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2014-01-20
    • 2021-05-28
    相关资源
    最近更新 更多