Take this really simple, fast and easy request to an API :
$page_limit;//number of items per page
$page_offset://number of items skipped
//This will get list of products
$url = "https://api.printful.com/sync/products
status=$product_status&offset=$page_offset&limit=$page_limit";
When I receive the response from the API I filter the array result by doing this :
//filter array with category name and gender chosen by USER
$category_array = array($category_name, $gender);
//filtering system
$product_array =(array_intersect_key($products['result'],
preg_grep('/(?=.*\b'.implode('\b)(?=.*\b', $category_array).'\b)/i',
array_column($products['result'], 'name'))));
This will show the products from the chosen category_name and gender for USER :
foreach($product_array as $product){
//show product
}
I paginate the result with this
//count number of total products in category
$row_count=count($product_array);
// make your LIMIT query here as shown above
// determine page number from $_GET
if(!empty($_GET['page']) && (isset($_GET['page']) )) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false == $page) {
$page = 1;
}
}else{
$page = 0;
}
// set the number of items to display per page
$items_per_page = $page_limit;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
// build query
$offset = ($page - 1) * $items_per_page;
I could do pagination easily if the API allowed me to request the entire list of products of course. However, it limits query to 100 requests per page. I'm bringing down to 20 per pages since it is much faster. So let's say I have total list of 75 products and limit 20 products per page. I have 26 Men T-Shirts in total.
Problem #1
If there are only 9 Men T-Shirts within the first 20 result set, the filtering system will count a total of 9 Men T-Shirts and create only 1 page. It should create 2 pages. Display 20 T-shirts on first page and 6 on second page.
Problem #2
If the filtering system cannot find any Men T-Shirts within the first 20 result set, the filtering system will display a blank page with no products and will create more blank pages to go through until it finds Men T-Shirts. So if it does not find any Men T-Shirts within the first 2 result set (first 2 pages), the user needs to turn the pages until the Men T-Shirts are found.
Now I know the problems could probably be solved with a math equation? I tried many and can't wrap my head around how to solve this issue.