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

时间:2016-01-27 22:21:40

标签: php

我希望编写一个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;
    }
}
?>

2 个答案:

答案 0 :(得分:2)

这样的东西? $ 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>

答案 1 :(得分:-2)

处理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是一种简单的循环方式。

我希望它有所帮助!