如何获取当前页码及分页结果?附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
$linksarray 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.
Corrected getLinks() Method
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
$linksarray, 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
forloop uses$j <= $this->pagesinstead of$j < ($this->pages + 1)for cleaner syntax.
内容的提问来源于stack exchange,提问作者carry0987
相关产品推荐
相关产品推荐

