【问题标题】:How to display random image from random directory如何显示随机目录中的随机图像
【发布时间】:2019-04-16 21:20:25
【问题描述】:

我正在尝试从随机目录中选择随机图像。我创建函数来获取随机目录和另一个函数从该目录中获取随机图像。好的,但它不起作用,它获取随机目录和来自另一个目录的随机图像

<?php

function showRandomDir()
    {
    $files = glob('images/portfolio/*/', GLOB_ONLYDIR);
    shuffle($files);
    $files = array_slice($files, 0, 1);
    foreach($files as $file)
        {
        return $file;
        }
    }

function rotate2()
    {
    $list = scandir(showRandomDir());
    $fileRotateList = array();
    $img = '';
    foreach($list as $fileRotate)
        {
        if (is_file(showRandomDir() . htmlspecialchars($fileRotate)))
            {
            $ext = strtolower(pathinfo($fileRotate, PATHINFO_EXTENSION));
            if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png')
                {
                $fileRotateList[] = $fileRotate;
                }
            }
        }

    if (count($fileRotateList) > 0)
        {
        $imageNumber = time() % count($fileRotateList);
        $img = showRandomDir() . urlencode($fileRotateList[$imageNumber]);
        }

    return $img;
    }

【问题讨论】:

标签: php image random directory


【解决方案1】:

rotate2() 函数的开头,调用showRandomDir() 以获取随机目录的内容:

$list = scandir(showRandomDir());

但最后,您再次调用showRandomDir(),因此您会得到一个不同的随机目录。
(嗯,一个目录,这可能不同,但可以随机相同。)

$img = showRandomDir() . urlencode($fileRotateList[$imageNumber]);

您需要将第一次调用保存到一个变量中,然后重复使用该变量而不是第二次调用showRandomDir()

$dir = showRandomDir();
$list = scandir($dir);
// ... the rest of the code in between
$img = $dir . urlencode($fileRotateList[$imageNumber]);

【讨论】:

  • 好的,但现在输出带有图像名称 -> images/portfolio/randomDir/
  • 抱歉,我不确定你的意思。你能再解释一下吗?
  • 对不起,它没有显示文件名,它只显示随机目录
  • 现在是 -> /images/portfolio/randomDir 应该是 /images/portfolio/randomDir/randomimage.jpg
  • 你现在收到了吗?
猜你喜欢
  • 2021-01-03
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多