Calculating item offset for pagination

2019-01-31 12:06发布

问题:

this seems like very simple maths but somehow, my brain cant think ...

i am trying to implement pagination and will need to calculate the item offset to use in limiting my result set. i am having problems calculating what index the first item of the page should have.

eg.

with 1 page having 10 items

page 1 will have items 1 - 10
page 2 ............... 11 - 20
page 3 ............... 21 - 30

i thought of

offset = page * itemsPerPage + 1

but this will not be the case for page 1. there must be a formula for this? am using PHP/Zend_Paginator/Doctrine2 but this should be language independent

wonder if this should be in the the maths stack exchange site

回答1:

Use offset = (page - 1) * itemsPerPage + 1.



回答2:

Honestly depends. I'm no PHP person, but I'll put both out there. If you are pulling your records in to some form of collection (list, array, etc.) then your formula should be:

offset = (page - 1) * itemsPerPage

This is because most (again, I'm not a PHP person) arrays and lists use 0 for their first element. If they do not use 0 for their first element and/or you're pulling from a table or something else where the IDs start at 1, then it should be:

offset = (page - 1) * itemsPerPage + 1

I hope that's clear and helps.



回答3:

  start = (page - 1) * itemsPerPage + 1
  end = totalItems

  if (itemsPerPage < totalItems) {
    end = itemsPerPage * page
    if (end > totalItems) {
      end = totalItems;
    }
  }

  // e.g. "21-30 of 193 items"
  start + '-' + end + ' of ' + totalItems + ' items'


回答4:

Using JS as an example, for progressive web app people...

JS arrays have the prototype method .slice(start, end) overview here it takes a start index and an end index as arguments.

I found the easiest way to calc both indexes is as follows;

Start Index

var start =  parseInt((selectedPage - 1) * resultsPerPage);

End Index

var end = parseInt(selectedPage * resultsPerPage);

Execution

var myPaginatedArray.slice(start, end);


回答5:

use this

$row_page = 5; //items per page

if(isset($_GET['p'])){
    $page_num = $_GET['p'];
} else {
    $page_num = 0;
}

$offset = ( $page_num ) * $row_page;

$cn = 31;

$pg = (int)ceil($cn / $row_page);

for ($i = 1; $i <= $pg; $i++){
    echo "<br/><a href='?p=$i'>".$i;
}


回答6:

I have faced this before in Angular 4, this is an edit of a piece of template with a list with pagination made simpler:

<div *ngFor="let item of pagedItems; let i = index">
  <div class="item-caption">
    Item {{(currentPage - 1) * itemsPerPage + (i + 1)}} of {{totalItemsDownloaded}}
  </div>
  <div class="item-name">{{item.name}}</div>
</div>

I have always handy currentPage as a result of clicking on Prev & Next buttons but initialized with 1, itemsPerPage as an App setting and totalItemsDownloaded is the count of total items the WebAPI call reported.

I hope it helps



标签: pagination