像stackoverflow一样的分页 [英] paging like stackoverflow's

查看:170
本文介绍了像stackoverflow一样的分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是php的新手,尤其是在进行分页时.

i'm a newbie in php especially on making pagination.

我的问题是,如何使分页像stackoverflow的分页一样?
我的意思是这样的分页:

1 ... 5 6 7 8 9 ... 25
(始终显示第一个数字和最后一个数字,但在中间只有5个数字,所选页面绝对在中间)

my question is, how to make paging like stackoverflow's pagination?
i mean paging like this :

1 ... 5 6 7 8 9 ... 25
(the first number and the last number is always appear, but in the middle only 5 numbers with the selected page absolutely in the middle)

在php中,我尝试进行分页,

in php i have tried making paging,

<?php

//Show page links
for($i=1; $i<=$pages; $i++)
{
    echo '<li id="'.$i.'">'.$i.'</li>';
}

?>

,但将显示所有页面,例如

1 2 3 4 5 6 7 8 9 10等

but it will be shown all of pages like

1 2 3 4 5 6 7 8 9 10 etc

有没有一个简单的逻辑例子可以解决这个问题?
非常感谢:)

any body have simple logic example to solve this problem?
many thanks :)

推荐答案

下面是常规分页类的摘录 1 我几年前写过.我已经对其进行了编辑,以仅显示相关部分.

Below is a snippet from a general pagination class1 I wrote a few years ago. I have edited it to show the relevant parts only.

// cntAround is the number of pages to show before and after the current
function renderNavigation($cntAround = 1) {
    $out      = '';
    $isGap    = false; // A "gap" is the pages to skip
    $current  = // Current page
    $cntPages = // Total number of pages

    for ($i = 0; $i < $pages; $i++) { // Run through pages
        $isGap = false;

        // Are we at a gap?
        if ($cntAround >= 0 && $i > 0 && $i < $cntPages - 1 && abs($i - $current) > $cntAround) { // If beyond "cntAround" and not first or last.
            $isGap    = true;

            // Skip to next linked item (or last if we've already run past the current page)
            $i = ($i < $current ? $current - $cntAround : $cntPages - 1) - 1;
        }

        $lnk = ($isGap ? '...' : ($i + 1)); // If gap, write ellipsis, else page number
        if ($i != $current && !$isGap) { // Do not link gaps and current
            $lnk = '<a href="?page=' . ($i + 1) . '">' . $lnk . '</a>';
        }
        $out .= "\t<li>" . $lnk . "</li>\n"; // Wrap in list items
    }

    return "<ul>\n" . $out . '</ul>'; // Wrap in list
}


示例1

cntAround = 1current = 5cntPages = 9:

[1] ... [4] 5 [6] ... [9]

示例2

cntAround = 3current = 5cntPages = 11:

[1] [2] [3] [4] 5 [6] [7] [8] ... [11]


1)文章用丹麦语. Google翻译版本


1) Article is in Danish. Google Translate'd version is here.

这篇关于像stackoverflow一样的分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆