【问题标题】:How to add limit when echoing images from a directory folder?从目录文件夹回显图像时如何添加限制?
【发布时间】:2017-03-23 08:13:08
【问题描述】:

下面是一个从目录文件夹中回显所有图像的脚本,它可以正常工作。但是,我只是试图将回显的图像数量限制为 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;
  }
}

【问题讨论】:

  • for ($i=1; $i
  • 我没有找到任何while循环?
  • for ($i=1; $i

标签: php directory glob


【解决方案1】:

就像拉曼已经说过,对 for 进行简单的修改就可以了

$maxImages = 8;

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

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

【讨论】:

    【解决方案2】:

    试试这个:

    $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>';   
    }
    

    希望对你有帮助。

    【讨论】:

    • 在显示图像之前如何检查目录是否为空?
    • 你可以使用 if(count($files)==0){}; }
    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 2017-05-02
    • 2018-09-22
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多