How to Paginate Lines in a Foreach Loop with PHP

How to Paginate lines in a foreach loop with PHP

A very elegant solution is using a LimitIterator:

$xml = simplexml_load_string($rawxml);
// can be combined into one line
$ids = $xml->xpath('id'); // we have an array here
$idIterator = new ArrayIterator($ids);
$limitIterator = new LimitIterator($idIterator, $offset, $count);
foreach($limitIterator as $value) {
// ...
}

// or more concise
$xml = simplexml_load_string($rawxml);
$ids = new LimitIterator(new ArrayIterator($xml->xpath('id')), $offset, $count);
foreach($ids as $value) {
// ...
}

Incrementing Operator in Foreach Loop for Pagination

In your view :

$links = $this->pagination->create_links();
$i = 1 + $this->pagination->cur_page*$this->pagination->per_page;

foreach($query->result() as $row){
echo $i++ . ') ';
echo $row->name . ' - ' . $row->email;
echo '<br>';
}

echo $links;

and you're cool.

Also, i'd recommend you use less echo, and only for php parts of your templating. For example, your code could be reformatted like this:

<?php $links = $this->pagination->get_links(); ?>

<ol start="<?php echo 1 + $this->pagination->cur_page*$this->pagination->per_page; ?>" >
<?php foreach($query->result() as $row) : ?>
<li><?php echo $row->name . ' - ' . $row->email; ?></li>
<?php endforeach; ?>
</ol>

<?php echo $links; ?>

Looks cleaner now, i think.

How to paginate a foreach loop?

You could determine which page is currently shown in a GET variable in your address

.../supporters.php?page=1

Then you could set the offset of your array_slice function accordingly

$nItemsPerPage = 2;
$page = isset($_GET['page'])?$_GET['page']:1;
array_slice($supporters, $nItemsPerPage*($page-1), $nItemsPerPage)

Pagination for foreach loop

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


Related Topics



Leave a reply



Submit