在PHP中每6次返回循环后,在文件夹中输出图像并清除浮动


Outputting images in folder and clearing float After Every 6 Returned In Loop in PHP

我试图计算我的文件夹中的图像,并希望从文件夹返回的每6个图像后清除浮动。这是我到目前为止得到的代码,但它吐出的数量比我想要的要多。谁能给我一个解决办法?提前感谢。下面是我的代码。

<?php
$i = 0;
$dirname = "images"; 
$images = scandir($dirname);
$filecount = count(glob("images/". "*.png"));
 //echo $filecount;
$ignore = Array(".", "..", "otherfiletoignore");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
if ($i % 6 === 0){
echo "<div style='clear:both;></div>'";
}
echo "<div style='float:left;'><img src='images/",$curimg."'"," /></div>";
}
}
?>

您永远不会改变$i的值,因此每次通过循环时它都将为零。在这种情况下,您需要使用for循环而不是foreach循环。

$images = glob("images/*.png");
$filecount = count($images);
$ignore = Array(".", "..", "otherfiletoignore");
for ($i = 0; $i < $filecount; $i++){
    if(!in_array($images[$i], $ignore)) {
        if ($i % 6 === 0){
                echo "<div style='clear:both;></div>'";
        }
        echo "<div style='float:left;'><img src='images/",$images[$i]."'"," /></div>";
    }
}

此代码将在每次迭代时输出echo "<div style='clear:both;></div>'";行。这是因为您没有在任何地方增加$i$i % 6 === 0总是为真,因为$i总是为零。

改变:

if(!in_array($curimg, $ignore)) {
if ($i % 6 === 0){

…:

if(!in_array($curimg, $ignore)) {
$i++;
if ($i % 6 === 0){

…或者使用for循环代替foreach