You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取当前页码及分页结果?附PHP分页代码问题咨询

Fixing Your Pagination to Get Current Page & Page Results

Hey there! Let's sort out your pagination code so it correctly returns all page links along with the active current page. Right now, there are two main issues with your existing code:

  • Syntax Error: The way you're assigning values to the $links array is incorrect (e.g., $links['active' => "$j"] isn't valid PHP syntax for associative arrays).
  • Data Loss: Even if you fixed the syntax, using the same key (pages_tag) for every non-active page would overwrite previous entries, leaving you with only the last non-active page in the array.

Here's an updated version that fixes both issues and properly structures the pagination data:

public function getLinks() {
    $links = array();
    // Only generate links if there's more than one page
    if ($this->pages > 1) {
        // Loop through all page numbers
        for ($j = 1; $j <= $this->pages; $j++) {
            // Determine the CSS class for the current page item
            $itemClass = $this->page === $j ? 'active' : 'pages_tag';
            // Add each page's data to the links array as an associative array
            $links[] = [
                'class' => $itemClass,
                'page' => $j
            ];
        }
        return $links;
    }
    // Return empty array if there's only one page (no pagination needed)
    return [];
}

Updated Usage

Now you can loop through the results correctly to render each page link:

$pageResult = $pagination->getLinks();
foreach ($pageResult as $pageItem) {
    echo "<a class=\"{$pageItem['class']}\">{$pageItem['page']}</a>";
}

Key Improvements

  • No Data Overwrites: Each page is stored as a separate entry in the $links array, so all page numbers are preserved.
  • Clear Structure: Each entry explicitly holds both the CSS class and page number, making the code easier to read and maintain.
  • Simplified Loop: The for loop uses $j <= $this->pages instead of $j < ($this->pages + 1) for cleaner syntax.

内容的提问来源于stack exchange,提问作者carry0987

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:29:35