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 limi
Thought I would add the following for displaying text like e.g:
Viewing 21-30 of 32 items.
In this example:
itemsPerPage = 10
page = 3
totalItems = 32
And there would be a total of 4 pages where the last page only has 2 items to display. The following worked for me:
(page - 1) * itemsPerPage + 1 + "-" +
Math.Min((page - 1) * itemsPerPage + itemsPerPage , totalItems ) + " of " +
totalItems + " items."
Sorry that is in C# strictly but the idea should be clear. Math.Min(x, y) returns the lower number of two parameters. There is probably an easier solution to calculate the upper bound without using Math.Min.
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'
I think this one is perfect and covers all scenario.
$offset = ($pageLimit * $page) - $pageLimit;
A simple pagination equation that covers all scenerio will be:
$page = $_GET['page'];
$items_per_page = 20; //for example
$offset = 0; //initial offset
if ($page != 1) {
$offset = ($page * $items_per_page) - $items_per_page;
}
Given items per page = 5
OUTPUT
when page = 1, offset = 0
when page = 2, offset = 5
when page = 3, offset = 10
when page = 4, offset = 15 . . .
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;
}
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