聘我网

新概念招聘3.0

PHP分页代码

vote up0vote downstar
function paginator($totalPages,$currentPage)
{
    if($currentPage > $totalPages)
        return false;
    $aheadmin = max(1,$currentPage - ($totalPages - $currentPage > 3 ? 2 : (5 - ($totalPages - $currentPage) -1)));

    if($aheadmin - 1 > 1)
    {
        $str = '1 ... ';
        $aftermax = min($currentPage + 2,$totalPages);
    }
    else if($aheadmin - 1 > 0)
    {
        $str = '1 ';
        $aftermax = min($currentPage + 1,$totalPages);
    }
    else
    {
        $str = '';
        $aftermax = min(5,$totalPages);
    }

    for($i = $aheadmin; $i <= $aftermax; $i++)
    {
        $str .= $i . ' ';
    }

    if($totalPages - $aftermax > 1)
        $str .= '.. ' . $totalPages;
    else if($totalPages - $aftermax > 0)
        $str .= $totalPages;
    return $str;
}
echo 'Total Pages:';
$total = trim(fgets(STDIN));
while(true)
{
    echo 'CurrentPage:';
    $current = trim(fgets(STDIN));
    echo paginator($total,$current) . "\r\n";
}

该分页函数第一个参数为总页数,第二个参数为当前页数

命令行运行上述代码即可看到效果

 
这个怎么在CMD下运行? 比如我把它放在C盘下的a写字板里 - nightwindw 2009-11-26, 04:10
先cd /d C:\进到目录,然后php paginator.php就行了。前提是php命令可用 - Shore 2009-11-26, 04:12
cd /d c:/a 命令提示“系统找不到制定的目录” php命令可用怎么讲? - nightwindw 2009-11-26, 04:19
你重新开个问题好了,这些评论与上面无关 - Shore 2009-11-26, 04:21

2 个答复

vote up0vote down
/*返回分页数据结构数组*/
function query_pager($pager, $total_pages, $num)
{
    $pager = ($pager < 1) ? 1 : ($pager > $total_pages ? $total_pages : $pager);
    $start = $pager - ($num - 1)/2;
    $start = $start < 1 ? 1 : $start;
    $end = $start + $num - 1;
    $end = $end > $total_pages ? $total_pages : $end;
    return array(
        'LEFT' => $start > 1 ? '...' : '',
        'START'=> $start,
        'END'  => $end,
        'RIGHT'=> $end < $total_pages ? '...' : ''
    );
}

例子:

$num = 5;
$paginatorArray = query_pager($_GET['pager'], $row['total'], $num);
链接
vote up0vote down

要注意的是,

在计算总页数时不能简单的$total_records/$number_per_page,

而应该是ceil($total_records/$number_per_page),

因为24/20结果是1.2,而我们其实想要的是2

链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.