简体   繁体   中英

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. This current code I have only posts them in separate rows. How can I divide them into rows of 8 images?

<?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.

<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. After having the correct loop, you can customize the html output any way you want.

<?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 ;)

foreach is a simple way to loop.

I hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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