2015-11-28 151 views
0

目前,我有我的「汽車類」即顯示在車內的方法:爲分頁foreach循環

 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內部,我有一個龐大的代碼,我將顯示的細節)

enter image description here

有沒有辦法實現分頁的東西,所以我可以每頁處理8輛汽車,而不是在同一頁面上顯示它們全部?

+1

你使用任何框架?我不知道DB :: select是什麼? – codenut

回答

0

你可以在你的函數添加$limit$page參數,以便它將只返回$limit * $page開始最大的$limit數量的項目(或將稱之爲$offset)。您還需要添加一個函數來獲取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>; 
    } 
} 
+0

先生,你是一個天才,它完美的作品! –