【问题标题】:display random image url from folder显示文件夹中的随机图像 url
【发布时间】:2013-01-13 07:56:44
【问题描述】:

我有一个 php 代码,它使用文件夹中的每个图像并在我的页面上回显 url。

我需要帮助的是让 php 代码在每次加载页面时随机化 url 列表。

我的代码是:

<?php 
 if ($handle = opendir('images')) {
   while (false !== ($file = readdir($handle)))
      {
          if ($file != "." && $file != "..")
      {
            $thelist .= '<div data-delay="5"><img src="images/'.$file.'"></div>';
          }
       }
  closedir($handle);
  }
?>
<?=$thelist?>

非常感谢

【问题讨论】:

  • 那么,有什么问题,你想要什么?

标签: php


【解决方案1】:

最简单的解决方案是将所有文件名放入一个数组中,然后使用shuffle() 将其混合。然后您可以遍历数组并输出图像。它应该看起来像这样:

<?php 
 $thelist = "";
 if ($handle = opendir('images')) {
   $images = array();
   while (false !== ($file = readdir($handle))) {
      if ($file != "." && $file != "..") {
            array_push($images, 'images/'.$file);
      }
   }
   closedir($handle);
   shuffle($images);
   foreach ($images as $image) {
      $thelist .= '<div data-delay="5"><img src="'.$image.'"></div>';
   }
   echo $thelist;
 }
?>

通过使用glob() 而不是opendir(),您可以显着缩短代码,因为glob() 返回一个数组,然后您只需要打乱那个数组。

【讨论】:

    【解决方案2】:

    将你的文件链接放入一个数组中,并使用函数shuffle() 对其进行洗牌

    <?php 
    
    if ($handle = opendir('images')) {
        $fileTab = array();
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $fileTab[] = $file; 
            }
        }
        closedir($handle);
        shuffle($fileTab);
        foreach($fileTab as $file) {
            $thelist .= '<div data-delay="5"><img src="images/'.$file.'"></div>';
        }
    }
    ?>
    <?=$thelist?>
    

    【讨论】:

      【解决方案3】:

      不是直接在while循环中创建div,而是仅使用它来将所有url存储在一个数组中。然后shuffel 该数组,并使用 foreach 循环来填充 $thelist。

      【讨论】:

        【解决方案4】:

        你为什么不用glob()

        $images = glob('images/*.{jpg,png,gif}', GLOB_BRACE);
        
        shuffle($images);
        
        foreach($images as $image) {
            echo '<div data-delay="5">
                      <img src="', $image ,'">
                  </div>';
        }
        

        【讨论】:

          猜你喜欢
          • 2014-01-30
          • 1970-01-01
          • 2020-01-07
          • 2012-06-10
          • 2011-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-18
          相关资源
          最近更新 更多