Jump to content

Foreach Loop Paginate ?


TomT

Recommended Posts

You would do the same as in a database pagination script, except the total number of rows is the count of your array entries, and instead of making a LIMIT clause in a query to define which rows are retrieved and displayed, you calculate the starting and ending array indexes.

 

Simple pagination script, modified to use an array as the data source -

 

<?php
// pagination from db -> array

$arr = range(1,32); // simulate data (index starts at 0)

$rows_per_page = 15;

// get total number of rows
/*
$query = "SELECT count(*) FROM table WHERE ...";
$result = mysql_query($query, $db);
list($numrows) = mysql_fetch_row($result);
*/
$numrows = count($arr);

// Calculate number of $lastpage
$lastpage = ceil($numrows/$rows_per_page);

// condition inputs/set default
if (isset($_GET['pageno'])) {
   $pageno = $_GET['pageno'];
} else {
   $pageno = 1;
}

// validate/limit requested $pageno
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
   $pageno = $lastpage;
}
if ($pageno < 1) {
   $pageno = 1;
}

// Find start and end array index that corresponds to the reuqeted pageno
$start = ($pageno - 1) * $rows_per_page;
$end = $start + $rows_per_page -1;

// limit $end to highest array index
if($end > $numrows - 1){
$end = $numrows - 1;
}

// database query
/*
$query = "SELECT * FROM table $limit";
$result = mysql_query($query, $db);
//... process contents of $result ...
*/

// display array from $start to $end
for($i = $start;$i <= $end;$i++){
echo $arr[$i] . '<br />';
}
echo "<br />";

// first/prev pagination hyperlinks
if ($pageno == 1) {
   echo " FIRST PREV ";
} else {
   echo " <a href='?pageno=1'>FIRST</a> ";
   $prevpage = $pageno-1;
   echo " <a href='?pageno=$prevpage'>PREV</a> ";
}

// Display current page or pages
echo " ( Page $pageno of $lastpage ) ";

// next/last pagination hyperlinks
if ($pageno == $lastpage) {
   echo " NEXT LAST ";
} else {
   $nextpage = $pageno+1;
   echo " <a href='?pageno=$nextpage'>NEXT</a> ";
   echo " <a href='?pageno=$lastpage'>LAST</a> ";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.