Php 如何显示随机目录中的随机图像

Php 如何显示随机目录中的随机图像,php,image,random,directory,Php,Image,Random,Directory,我正在尝试从随机目录中选择随机图像。我创建了获取随机目录的函数和从该目录获取随机图像的另一个函数。好的,但它不工作,它从另一个目录获取随机目录和随机图像 <?php function showRandomDir() { $files = glob('images/portfolio/*/', GLOB_ONLYDIR); shuffle($files); $files = array_slice($files, 0, 1); foreach($fi

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

<?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;
    }

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

$list = scandir(showRandomDir());
但在最后,您再次调用
showdrandomdir()
,因此您会得到一个不同的随机目录。
(好吧,一个新的,可能不同,但可能随机相同。)

您需要将第一次调用保存到一个变量中,并重用该变量,而不是第二次调用
showdrandomdir()

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

我认为随机是一个神话:好吧,但现在输出的是图像名->图像/portfolio/randomDir/对不起,我不知道你说的是什么意思。你能再解释一下吗?对不起,它没有显示文件名,它只显示随机目录现在是->/images/portfolio/randomDir,应该是/images/portfolio/randomDir/randomDir.jpgDid你现在知道了吗?
$dir = showRandomDir();
$list = scandir($dir);
// ... the rest of the code in between
$img = $dir . urlencode($fileRotateList[$imageNumber]);