7

我有一个脚本可以动态调用和显示目录中的图像,最好的分页方式是什么?我希望能够通过脚本中的变量控制每页显示的图像数量。我正在考虑使用 URL 变量(即 - http://domain.com/page.php?page=1),但我不确定如何去做。

谢谢您的帮助。

4

4 回答 4

10

这是我经常用来做分页的功能。希望能帮助到你。

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
)

有了所有这些数据,您就可以很好地制作分页链接。

于 2008-10-16T04:40:38.367 回答
9

分页是有或没有 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
}

希望能帮助您入门!

于 2008-10-16T03:01:42.560 回答
0

如果您将图像命名为 01.jpg、02.jpg,则可以更轻松地进行分页。然后使用 glob 将所有图像放入一个数组并对其进行排序。

于 2008-10-16T04:09:52.720 回答
0

如有疑问,请使用 javascript!这也可能有帮助:http ://www.webplicity.net/flexigrid/

可能对类似画廊的应用程序有好处,尽管我从未尝试过:)

于 2008-10-16T20:17:59.833 回答