찾다
php教程PHP源码万能的分页类

万能的分页类

May 23, 2016 pm 01:07 PM


init(1000, 20);
 * $page->setNotActiveTemplate(' {a} ');
 * $page->setActiveTemplate('{a}');
 * echo $page->show();
 * 
 * 
 * @author 风居住的地方
 */
class Page {
    /**
     * 总条数
     */
    private $total;
    /**
     * 每页大小
     */
    private $pageSize;
    /**
     * 总页数
     */
    private $pageNum;
    /**
     * 当前页
     */
    private $page;
    /**
     * 地址
     */
    private $uri;
    /**
     * 分页变量
     */
    private $pageParam;
    /**
     * LIMIT XX,XX
     */
    private $limit;
    /**
     * 数字分页显示
     */
    private $listnum = 8;
    /**
     * 分页显示模板
     * 可用变量参数
     * {total}      总数据条数
     * {pagesize}   每页显示条数
     * {start}      本页开始条数
     * {end}        本页结束条数
     * {pagenum}    共有多少页
     * {frist}		首页
     * {pre}		上一页
     * {next}		下一页
     * {last}		尾页
     * {list}		数字分页
     * {goto}		跳转按钮
     */
    private $template = '共有{total}条数据每页显示{pagesize}条数据,本页{start}-{end}条数据共有{pagenum}页{frist}{pre}{list}{next}{last}{goto}';
    /**
     * 当前选中的分页链接模板
     */
    private $activeTemplate = '{text}';
    /**
     * 未选中的分页链接模板
     */
    private $notActiveTemplate = '{text}';
    /**
     * 显示文本设置
     */
    private $config = array('frist' => '首页', 'pre' => '上一页', 'next' => '下一页', 'last' => '尾页');
    /**
     * 初始化
     * @param type $total       总条数
     * @param type $pageSize    每页大小
     * @param type $param       url附加参数
     * @param type $pageParam   分页变量
     */
    public function init($total, $pageSize, $param = '', $pageParam = 'page') {
        $this->total = intval($total);
        $this->pageSize = intval($pageSize);
        $this->pageParam = $pageParam;
        $this->uri = $this->geturi($param);
        $this->pageNum = ceil($this->total / $this->pageSize);
        $this->page = $this->setPage();
        $this->limit = $this->setlimit();
    }
    
    /**
     * 设置分页模板
     * @param type $template    模板配置
     */
    public function setTemplate($template) {
        $this->template = $template;
    }
    
    /**
     * 设置选中分页模板
     * @param type $activeTemplate      模板配置
     */
    public function setActiveTemplate($activeTemplate) {
        $this->activeTemplate = $activeTemplate;
    }

    /**
     * 设置未选中分页模板
     * @param type $notActiveTemplate   模板配置
     */
    public function setNotActiveTemplate($notActiveTemplate) {
        $this->notActiveTemplate = $notActiveTemplate;
    }

    /**
     * 返回分页
     * @return type
     */
    public function show() {
        return str_ireplace(array(
            '{total}',
            '{pagesize}',
            '{start}',
            '{end}',
            '{pagenum}',
            '{frist}',
            '{pre}',
            '{next}',
            '{last}',
            '{list}',
            '{goto}',
        ), array(
            $this->total,
            $this->setPageSize(),
            $this->star(),
            $this->end(),
            $this->pageNum,
            $this->frist(),
            $this->prev(),
            $this->next(),
            $this->last(),
            $this->pagelist(),
            $this->gopage(),
        ), $this->template);
    }
    
    /**
     * 获取limit起始数
     * @return type
     */
    public function getOffset() {
        return ($this->page - 1) * $this->pageSize;
    }
    
    /**
     * 设置LIMIT
     * @return type
     */
    private function setlimit() {
        return "limit " . ($this->page - 1) * $this->pageSize . ",{$this->pageSize}";
    }

    /**
     * 获取limit
     * @param type $args
     * @return type
     */
    public function __get($args) {
        if ($args == "limit") {
            return $this->limit;
        } else {
            return null;
        }
    }

    /**
     * 初始化当前页
     * @return int
     */
    private function setPage() {
        if (!empty($_GET[$this->pageParam])) {
            if ($_GET[$this->pageParam] > 0) {
                if ($_GET[$this->pageParam] > $this->pageNum)
                    return $this->pageNum;
                else
                    return $_GET[$this->pageParam];
            }
        }
        return 1;
    }

    /**
     * 初始化url
     * @param type $param
     * @return string
     */
    private function geturi($param) {
        $url = $_SERVER['REQUEST_URI'] . (strpos($_SERVER['REQUEST_URI'], "?") ? "" : "?") . $param;
        $parse = parse_url($url);
        if (isset($parse["query"])) {
            parse_str($parse["query"], $params);
            unset($params["page"]);
            $url = $parse["path"] . "?" . http_build_query($params);
            return $url;
        } else {
            return $url;
        }
    }

    /**
     * 本页开始条数
     * @return int
     */
    private function star() {
        if ($this->total == 0) {
            return 0;
        } else {
            return ($this->page - 1) * $this->pageSize + 1;
        }
    }

    /**
     * 本页结束条数
     * @return type
     */
    private function end() {
        return min($this->page * $this->pageSize, $this->total);
    }

    /**
     * 设置当前页大小
     * @return type
     */
    private function setPageSize() {
        return $this->end() - $this->star() + 1;
    }
    
    /**
     * 首页
     * @return type
     */
    private function frist() {
        $html = '';
        if ($this->page == 1) {
            $html .= $this->replace("{$this->uri}&page=1", $this->config['frist'], true);
        } else {
            $html .= $this->replace("{$this->uri}&page=1", $this->config['frist'], false);
        }
        return $html;
    }

    /**
     * 上一页
     * @return type
     */
    private function prev() {
        $html = '';
        if ($this->page > 1) {
            $html .= $this->replace($this->uri.'&page='.($this->page - 1), $this->config['pre'], false);
        } else {
            $html .= $this->replace($this->uri.'&page='.($this->page - 1), $this->config['pre'], true);
        }
        return $html;
    }

    /**
     * 分页数字列表
     * @return type
     */
    private function pagelist() {
        $linkpage = "";
        $lastlist = floor($this->listnum / 2);
        for ($i = $lastlist; $i >= 1; $i--) {
            $page = $this->page - $i;
            if ($page >= 1) {
                $linkpage .= $this->replace("{$this->uri}&page={$page}", $page, false);
            } else {
                continue;
            }
        }
        $linkpage .= $this->replace("{$this->uri}&page={$this->page}", $this->page, true);
        for ($i = 1; $i page + $i;
            if ($page pageNum) {
                $linkpage .= $this->replace("{$this->uri}&page={$page}", $page, false);
            } else {
                break;
            }
        }
        return $linkpage;
    }

    /**
     * 下一页
     * @return type
     */
    private function next() {
        $html = '';
        if ($this->page < $this->pageNum) {
            $html .= $this->replace($this->uri.&#39;&page=&#39;.($this->page + 1), $this->config[&#39;next&#39;], false);
        } else {
            $html .= $this->replace($this->uri.&#39;&page=&#39;.($this->page + 1), $this->config[&#39;next&#39;], true);
        }
        return $html;
    }

    /**
     * 最后一页
     * @return type
     */
    private function last() {
        $html = &#39;&#39;;
        if ($this->page == $this->pageNum) {
            $html .= $this->replace($this->uri.&#39;&page=&#39;.($this->pageNum), $this->config[&#39;last&#39;], true);
        } else {
            $html .= $this->replace($this->uri.&#39;&page=&#39;.($this->pageNum), $this->config[&#39;last&#39;], false);
        }
        return $html;
    }

    /**
     * 跳转按钮
     * @return string
     */
    private function gopage() {
        $html = &#39;&#39;;
        $html.=&#39; &#39;;
        return $html;
    }

    /**
     * 模板替换
     * @param type $replace     替换内容
     * @param type $result      条件
     * @return type
     */
    private function replace($url, $text, $result = true) {
        $template = ($result ? $this->activeTemplate : $this->notActiveTemplate);
        
         $html = str_replace(&#39;{url}&#39;, $url, $template);
         $html = str_replace(&#39;{text}&#39;, $text, $html);
        return $html;
    }
}

                   

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.