400+图片的PHP分页


PHP pagination of 400+ pictures

a 有一个目录中有 400 多张图片的网站。我想在每页上按 12 列出它们。我该怎么做?这是我的实际代码:

 <!doctype html>
<html lang="hu">
    <head>
        <title>Amatőr</title>
        <meta charset="utf-8"/>
    </head>
    <body>
        <h2><a href="../php/upload_picture.php" style="font-size:15pt; color:#ff00e8; text-decoration: none;">Vannak jó képeid? Töltsd fel őket és kikerülhetnek az oldalra!</a></h2>
        <article>
            <header>
                Amatőr Lányok
            </header>
            <div id="kepek">
                <?php
                $imgdir = '../img/blog/img/amator/'; //Pick your folder
                $allowed_types = array('png','jpg','jpeg','gif'); //Allowed types of files
                $dimg = opendir($imgdir);//Open directory
                while($imgfile = readdir($dimg))
                {
                  if( in_array(strtolower(substr($imgfile,-3)),$allowed_types) OR
                      in_array(strtolower(substr($imgfile,-4)),$allowed_types) )
                /*If the file is an image add it to the array*/
                  {$a_img[] = $imgfile;}
                }

                 $totimg = count($a_img);  //The total count of all the images
                //Echo out the images and their paths incased in an li.
                 for($x=0; $x < $totimg; $x++){ echo "<a onclick='Lightbox.start(this, false, false, false, false); return false;' rel='lightbox[amator]' href='" . $imgdir . $a_img[$x] . "'><img class='kep_listaz' width='200px' height='160px' src='" . $imgdir . $a_img[$x] . "' /></a>";}
                ?>
            </div>
        </article>
    </body>
</html>
Thanks!

所以这实际上更像是一个数学问题。您需要获取图像的总数,然后将其除以每页的最大图像数(确保ceil()它)。

现在,查看所有这些图像所需的最大页数。您现在需要做的是确定是要页面= 1/page = 2等还是作为开始和结束。但是,两者都相对容易,使用您需要做的页面

$page = (int)$_GET['page'];
$start = $page * $max_items_per_page;
$end = $start + $max_items_per_page;

这样它可能会节省下来。还要添加额外的代码,以确保您不会超出请求页面的范围。

现在就是获取文件数组的问题(我建议您使用glob())并从头到尾使用它array_slice()

最后,只需有一个上一页/下一页,或列出所有(或部分)页面。获取下一个和上一个就像添加/删除 1 到 $page 一样简单,即 $next = $page + 1;$prev = $page-1; .同样,对于这两个,请仔细检查您是否越界。如果它们超出界限,最好不要显示下一个/上一个。

有两种

方法可以对此类数据进行分页:在前端,您发送所有数据,JavaSctipt 一次只向用户显示一部分,或者在后端,一次只呈现一部分页面,然后重新加载整个页面以获取更多信息。

使其工作的最快方法是使用后端方法:

在 for 循环之前添加$page = isset($_GET['page']) ? $_GET['page']-1 : 0;

将循环的参数更改为$x=$page*12; $x < $totimg && $x < ($page+1)*12; $x++

然后,您可以通过向 url 添加?page=3来操作页面

您还需要添加一些错误处理,以防提交无效的页码。