每行显示两张图像,最多 4 张


$dir = dir("/adunits/");
$file_count = 0;
while ($file = $dir->read()) {
    if($file != "." && $file != "..") {
        if (!is_dir($curpath.$file)) {
           $files[$file_count] = $file;
        $file_count = $file_count + 1;
        } // not a directory
    } // not . or ..
} // read through dir
$dir->close();
shuffle($files);
echo "<h4 class="widgettitle">Sponsors</h4>";
for ($i = 0; $i <= $file_count-1; $i++) {
        $target = "http://" . str_replace(".jpg", "", $files[$i]);
    if (file_exists("/adunits/$files[$i]")) {
        echo "<center><div class="adunit_position"><a href="$target" target="_new"><img class="adunit" src="http://temp.com/adunits/$files[$i]" alt="$files[$i]" /></a></div></center>";
    }
}

我需要修改它以每行显示两个图像,最多显示 4 个图像。现在该目录只有 4 张图像,但在不久的将来它会有更多......大概像100。

我没有写这段代码,我正在尝试学习和成长我的php知识。

提前感谢您的帮助。

关于最大图像数,您可以创建一个默认值为 4 的变量,例如 $maxImages = 4;,然后根据文件计数更改此值,然后循环遍历$maxImages。

我会考虑稍微更改 HTML 标记以使用无序列表<ul><li></li></ul>并使用 CSS 将一行上的图像数量限制为 2。在下面的示例(未经测试)中,我使用了第 n 种类型和 CSS 浮点数,但是可能有更现代/更好的方法来实现所需的结果。https://css-tricks.com/almanac/selectors/n/nth-of-type/我还替换了回声";通过中断和退出 PHP,允许更好的语法突出显示。 还意味着您无需使用转义字符即可使用双引号。 我会说看看 http://php.net/manual/en/language.types.string.php 以了解有关单引号和双引号用法的更多信息。

<?php
$dir = dir("/adunits/");
$i = 0;
while ($file = $dir->read()) {
    if($file != "." && $file != "..") {
        if (!is_dir($curpath.$file)) {
           $files[$i] = $file;
           $i++;
        } // not a directory
    } // not . or ..
} // read through dir
$dir->close();
shuffle($files);
$maxImages = 4;
$file_count = count($files);
if($file_count < 4) {
    $maxImages = $file_count;
}
?>
<h4 class="widgettitle">Sponsors</h4>
    <ul class="adunit_list">
    <?php
        for ($i = 0; $i < $maxImages; $i++) {
            $target = "http://" . str_replace(".jpg", "", $files[$i]);
            if (file_exists("/adunits/$files[$i]")) { ?>
                <li class="adunit_position"><a href="<?php echo $target ?>" target="_new"><img class="adunit" src="http://temp.com/adunits/<?php echo $files[$i]?>" alt="<?php echo $files[$i]?>" /></a></li>;
                <?php
            }
        } ?>
    </ul>
<style>
.adunit_list li {
    float: left;
}
.adunit_list li:nth-of-type(2n+1) {
    clear:  both;
}

最新更新