使用glob的PHP分页来检索图像 [英] PHP pagination using glob to retrieve images
本文介绍了使用glob的PHP分页来检索图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用glob()从文件夹中检索图像,并且希望将其分页,以便每页仅显示3张图像.
I'm trying to retrieve images from a folder using glob() and i want it to be paginated so it only displays 3 images per page.
在互联网上以及在S.O上进行挖掘.我有下面的代码.问题在于它仅从目录中提取三张图像,当我单击下一页时,它会显示相同的三张图像.
From digging around on the internet and here on S.O. i've got the code below. The problem is that it only pulls three images from the directory and when i click on the next page it shows the same 3 images.
使用glob为每个页面获取不同图像的最佳方法是什么?
What would be the best way to fetch different images for each page using glob?
$imagesDir = 'uploadedImages/thumbs/*';
$itemsPerPage = 3;
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$totalItems = getTotalItems($imagesDir);
$totalPages = ceil($totalItems / $itemsPerPage);
getItemsFromPage($currentPage, $itemsPerPage, $imagesDir);
getPager($totalPages, $currentPage);
//counts the number of files in the dir
function getTotalItems($imagesDir) {
$numImages = count(glob($imagesDir));
return $numImages;
}
//gets the files from the dir
function getItemsFromPage($page, $numItems, $dir) {
$x = 0;
//get the first 3 items from the
foreach(glob($dir) as $image)
{
if($x < $numItems)
{
echo "<li><img src=\"$image\" alt=\"$image\" /></li>";
$x++;
}
else
{
break;
}
}
}
//creates the pages and the links
function getPager($totalPages, $currentPage) {
// if we're not on the first page, show the previous page and first page links
if($currentPage > 1)
{
$prevPage = $currentPage - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevPage'><</a> ";
}
$range = 1;
// show what page we're on and the page numbers surround this page
for($x = ($currentPage - $range); $x < ($currentPage + $range) +1; $x++)
{
if(($x > 0) && ($x <= $totalPages))
{
if($x == $currentPage)
{
echo " [<b>$x</b>] ";
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?currentPage=$x'>$x</a> ";
}
}
}
// if we're not on the last page show the next page and last page links
if($currentPage != $totalPages)
{
$nextPage = $currentPage + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextPage'>></a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalPages'>>></a> ";
}
}
推荐答案
function getItemsFromPage($page, $numItems, $dir) {
$offset = ($page - 1) * $numItems;
$x = 0;
//get the first 3 items from the
foreach(glob($dir) as $image)
{
if($x < $offset)
{
$x++;
}
elseif($x < $numItems + $offset)
{
echo "<li><img src=\"$image\" alt=\"$image\" /></li>";
$x++;
}
else
{
break;
}
}
}
这篇关于使用glob的PHP分页来检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文