繁体   English   中英

在html表中显示图像(IF循环)

[英]Display images in html table (IF loop)

我正在寻找编写一个PHP脚本,该脚本会将来自目录的图像发布为8列宽的表格格式,并且行扩展的图像数与原来一样。 当前代码中我仅将它们发布在单独的行中。 如何将它们分成8张图像的行?

<?php

$files = glob("images/*.*");
for ($i=1; $i<count($files); $i++)
{
    $image = $files[$i];
    $supported_file = array(
        'gif',
        'jpg',
        'jpeg',
        'png'
    );

    $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
    if (in_array($ext, $supported_file)) {
        // print $image ."<br />";
        echo '<a href="' .$image .'"><img src="'.$image .'" alt="Random image" width=200 /></a>'."<br /><br />";
    } else {
        continue;
    }
}
?>

像这样吗 $ i%8每8行返回0,所以我们要做的就是基本上停止/启动<tr>标记。

<table>
    <tr>
        <?php
        $files = glob("images/*.*");
        for ($i = 1; $i < count($files); $i++) {
            $image = $files[$i];
            $supported_file = array(
                'gif',
                'jpg',
                'jpeg',
                'png'
            );

            $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
            if (in_array($ext, $supported_file)) {
                // print $image ."<br />";
                echo '<td><a href="' . $image . '"><img src="' . $image . '" alt="Random image" width=200 /></a></td>';
            }
            if ($i % 8 === 0) {
                echo "</tr><tr>";
            }
        }
        ?>
    </tr>
</table>

处理glob的更简单方法是使用foreach。 正确循环后,您可以根据需要自定义html输出。

<?php

foreach (glob('images/*.{gif,jpg,jpeg,png}', GLOB_BRACE) as $image) {
  echo '<a href="' .$image .'"><img src="'.$image .'" alt="Random image" width=200 /></a>'."<br /><br />";
}

glob接受标志GLOB_BRACE ,这有时非常有用;)

foreach是循环的简单方法。

希望对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM