|
Pagination as seen on Evil Walrus |
|
This is a striped down version of the code used to generate the tabs in
the search results pages. This function returns an array of the page
numbers to be displayed. The array keys are ordered as they should be
displayed (you could simply cycle through the array with foreach to
display the page numbers). It will return a maximum of 15 page numbers,
and if there are more than 15 page numbers, it will show the first
and/or last 2 page numbers of the results. The array values represent
the page number, and array values that are '0' represent where extra
page numbers have been truncated.
-
<?php
-
// written by Aaron Hall, evilwalrus.org
-
// free to copy, modify and redistribute without consent
-
-
function generatePagination($curPage, $totResults, $resultsPerPage)
-
{
-
$totPages = ceil($totResults / $resultsPerPage);
-
-
$pagesBefore = $curPage - 1;
-
$pagesAfter = $totPages - $curPage;
-
-
-
-
if($totPages > 15) {
-
-
if($pagesBefore > 7) {
-
-
-
if($pagesAfter > 7)
-
{
-
for($i=($curPage-(4)); $i<$curPage; $i++) { $tabArr[] = $i; }
-
} else {
-
for($i=($totPages-11); $i<$curPage; $i++) { $tabArr[] = $i; }
-
}
-
} else {
-
for($i=1; $i<$curPage; $i++) { $tabArr[] = $i; }
-
}
-
-
$tabArr[] = $curPage;
-
-
if($pagesAfter > 7) {
-
if($pagesBefore > 7) {
-
for($i=($curPage+1); $i<=$curPage+4; $i++) { $tabArr[] = $i; }
-
} else {
-
for($i=($curPage+1); $i<13; $i++) { $tabArr[] = $i; }
-
}
-
$tabArr[] = 0;
-
$tabArr[] = $totPages-1;
-
$tabArr[] = $totPages;
-
} else {
-
for($i=($curPage+1); $i<=$totPages; $i++) { $tabArr[] = $i; }
-
}
-
-
} else {
-
for($i=1;$i<=$totPages;$i++) { $tabArr[] = $i; }
-
}
-
-
return $tabArr;
-
-
}
-
-
print_r(generatePagination (2, 400, 20)); // passes arguments 'current page number', 'total results', and 'results per page' respectively
-
?>
-
-
Returns:
-
-
Array
( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] =>
6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 [10] => 11 [11]
=> 12 [12] => 0 [13] => 19 [14] => 20 )
-
-
Here's an example usage:
-
-
<?
-
-
$currentPage = (empty($currentPage)) ? '1' : $_GET['page']; // the page the user is currently viewing -- set the $currentPage to 1 if empty, otherwise $_GET['page']
-
$totalResults = 400; // total query results -- would probably come from mysql_num_rows on a non-limited query
-
$listingsPerPage = 20; // how many results are being listed per page
-
-
$paginationArray = generatePagination($currentPage, $totalResults, $listingsPerPage);
-
-
foreach($paginationArray as $page) {
-
-
if($page == 0) {
-
echo "..."; // print an elipse, representing pages that aren't displayed
-
} else {
-
echo "[<a href="listing.php?page= $page">$page</a>]";
-
}
-
-
echo " "; // space the pages
-
}
-
-
?>
-
-
returns
"[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] ...
[19] [20]", with each as a link pointing to listing.php?page=$page
|