简体   繁体   English

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

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

I'm looking to write a PHP script that will post images from a directory into a table format that is 8 columns wide and the rows extend as many images as there are. 我正在寻找编写一个PHP脚本,该脚本会将来自目录的图像发布为8列宽的表格格式,并且行扩展的图像数与原来一样。 This current code I have only posts them in separate rows. 当前代码中我仅将它们发布在单独的行中。 How can I divide them into rows of 8 images? 如何将它们分成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;
    }
}
?>

Something like this? 像这样吗 $i % 8 returns 0 every 8th row so all we do is stop stop/start the <tr> tag basically. $ 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>

A simpler way to handle glob is using foreach. 处理glob的更简单方法是使用foreach。 After having the correct loop, you can customize the html output any way you want. 正确循环后,您可以根据需要自定义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 accepts the flag GLOB_BRACE , which is a very useful sometimes ;) glob接受标志GLOB_BRACE ,这有时非常有用;)

foreach is a simple way to loop. foreach是循环的简单方法。

I hope it helps! 希望对您有所帮助!

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

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