PHP以列显示图像

时间:2014-05-22 11:03:29

标签: php html css image gallery

我最近在四个相同宽的方框中显示了一个图像库,图像宽度为100%,两者都清晰,高度自动。这很好用,除了我在页面上调用了数百个图像。

我试图获得相同的效果,只使用一个简短的PHP脚本来调用图像并显示它们。

Here is a link to the gallery before

And here is a link to the site which I am trying to achieve the 4 column fetch thing on.

我目前拥有的PHP代码

<?php 
    $dir    = 'images/gallery/';
    $files  = scandir($dir);
    $images = array();

    foreach($files as $file) 
    {
        if(fnmatch('*.jpg',$file)) 
        {
            $images[] = $file;
        }
    }

    foreach($images as $image) 
    {
        echo '<img src="images/gallery/'.$image.'" />';
    }
?>

1 个答案:

答案 0 :(得分:0)

试试这段代码

  $dir    = 'images/gallery/';
    $files  = scandir($dir);
    $images = array();


    foreach($files as $file) 
    {
        if(fnmatch('*.jpg',$file)) 
        {
            $images[] = $file;
        }
    }

    $image_count = count($images);
    $count_each_column = ceil($image_count/4);

    echo '<div style="width:100%; max-width:950px; margin:0 auto;">';
    $count = 0;
    foreach($images as $image) 
    {
        $count+=1;
        if($count==1)
        {
            echo '<div class="box boxgallery">';
        }

            echo '<img src="images/gallery/'.$image.'" />';

        if($count>=$count_each_column)
        {
            $count=0;
            echo '</div>';
        }
    }

    if($count>0)
    {
        echo '</div>';
    }
    echo '</div>';

和一些 CSS

<style>
.boxgallery {
    margin: 0 0.6% 0 0;
    padding: 0;
    width: 24%;
    float:left;
}

.boxgallery img {
    clear: both;
    float: left;
    height: auto;
    margin-bottom: 2%;
    transition: opacity 0.3s ease 0s;
    width: 100%;
}

</style>