Php foreach循环的分页
我目前在我的“汽车类”中有一个显示汽车的方法:Php foreach循环的分页,php,pagination,Php,Pagination,我目前在我的“汽车类”中有一个显示汽车的方法: static function getCars(){ $autos = DB::query("SELECT * FROM automoviles"); $retorno = array(); foreach($autos as $a){ $automovil = automovil::fromDB($a->marca, $a->modelo, $a-
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辆车,而不是在同一页上显示所有车?您可以在函数中添加
$limit
和$page
参数,这样它最多只能返回$limit
从$limit
*开始的项数$page
(或将其称为$offset
)。您还需要添加一个函数来获取自动移动文件
表的行总数
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>;
}
}
$total=car::getTotal();
如果($total>8){
对于($i=1;$i),您是否使用任何框架?我不确定DB::select是什么?