问题
I recently had an image gallery displayed nicely in four equally wide boxes, with the images as 100% width, clear both and height auto. This worked pretty well, except I had hundreds of images called on the page.
I am trying to get the same effect, only using a short php script to call the images and display them.
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.
And the php code I currently have
<?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:
try this code
$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>';
and Some 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>
来源:https://stackoverflow.com/questions/23805015/php-display-images-in-columns