从目录文件夹回显图像时如何添加限制?

How to add limit when echoing images from a directory folder?

下面是一个从目录文件夹中回显所有图像的脚本,它没有任何问题。但是,我只是想将回显的图像数量限制在 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)) {
    echo '<div class="col-md-6 col-xs-4">';   
    echo '<img src="'.$image .'" alt="Random image"  class="your_images" />'."<br /><br />";
    echo '</div>';   
  } else {
    continue;
  }
}

就像 Raman 已经说过的那样,对 for 进行简单的修改就可以了

$maxImages = 8;

for ($i=1; $i<=count($files) && $i<=$maxImages; $i++) {
    // do your stuff
}

如果您的文件夹中没有 8 张图片,您需要计算图片数量

试试这个:

$limit = 8; // number of images
$start = 0;// or $start = count($$files)-$limit)
$files = glob("images/*.{jpeg,jpg,png,gif}", GLOB_BRACE);
$limit = ((count($files))>$limit)? $limit : count($files);// to take into account situation where we have less than 8 images
foreach(array_slice($files,$start, $limit) as $image){ 
echo '<div class="col-md-6 col-xs-4">';   
    echo '<img src="'.$image .'" alt="Random image"  class="your_images"     />'."<br/><br/>";
    echo '</div>';   
}

希望对您有所帮助。