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?

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