我有一个动态调用并显示目录图像的脚本,这对于分页是最好的方法吗?我希望能够通过脚本中的变量控制每页显示的图像数量.我正在考虑使用URL varriables(即http://domain.com/page.php?page=1),但我不确定如何解决这个问题.
谢谢您的帮助.
这是我经常用来做分页的功能.希望能帮助到你.
function paginate($page, $total, $per_page) { if(!is_numeric($page)) { $page = 1; } if(!is_numeric($per_page)) { $per_page = 10; } if($page > ceil($total / $per_page)) $page = 1; if($page == "" || $page == 0) { $page = 1; $start = 0; $end = $per_page; } else { $start = ($page * $per_page) - ($per_page); $end = $per_page; } $prev_page = ""; $next_page = ""; $all_pages = array(); $selected = ""; $enabled = false; if($total > $per_page) { $enabled = true; $prev = $page - 1; $prev_page = ($prev == 0) ? 0 : $prev; $next = $page + 1; $total_pages = ceil($total/$per_page); $next_page = ($next <= $total_pages) ? $next : 0; for($x=1;$x<=$total_pages;$x++) { $all_pages[] = $x; $selected = ($x == $page) ? $x : $selected; } } return array( "per_page" => $per_page, "page" => $page, "prev_page" => $prev_page, "all_pages" => $all_pages, "next_page" => $next_page, "selected" => $selected, "start" => $start, "end" => $end, "enabled" => $enabled ); } // ex: we are in page 2, we have 50 items, and we're showing 10 per page print_r(paginate(2, 50, 10));
这将返回:
Array ( [per_page] => 10 [page] => 2 [prev_page] => 1 [all_pages] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) [next_page] => 3 [selected] => 2 [start] => 10 [end] => 10 [enabled] => 1 )
有了所有这些数据,你就可以很好地武装到分页链接.
分页是与sql相同的概念.你只需要你的基本变量,然后就可以创建你想要的内容了.这是一些准代码:
$itemsPerPage = 5; $currentPage = isset($_GET['page']) ? $_GET['page'] : 1; $totalItems = getTotalItems(); $totalPages = ceil($totalItems / $itemsPerPage); function getTotalItems() { // since they're images, perhaps we'll scan a directory of images to determine // how many images we have in total } function getItemsFromPage($page, $itemsPerPage) { // function to grab $itemsPerPage based on which $page we're on } function getPager($totalPages, $currentPage) { // build your pager }
希望能帮助您入门!