dp411805872 2015-11-28 03:46
浏览 115
已采纳

foreach循环的分页

I currently have a method inside my "car class" that display the car:

        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;
    }

In my index.php I call that function

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

That allows me to display the info this way ( of course inside the foreach I have a huge code with the details I'll display.

enter image description here

Is there a way to implement a pagination to that thing so I can handle 8 cars per page, instead of showing all of them at the same page?

  • 写回答

1条回答 默认 最新

  • dongtiaobeng7901 2015-11-28 04:52
    关注

    You can add a $limit and $page parameter on your function so that it will only return a maximum of $limit number of items starting from $limit * $page(or will call it the $offset). You also need to add a function to get the total number of rows you have for automoviles table.

    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
    }
    

    In your index.php do this:

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

    and add the pagination links.

    $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>;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧