来自目录的PHP图像 - 随机顺序

0 php random directory image

我有一个我用来存储参考图像的网站页面..

目前我只是将所有图像放到我服务器上的目录中,php会显示我喜欢的内容.

我想问的是,每次刷新页面时,如何让它们以不同的随机顺序显示?

代码如下:

$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');


if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);


foreach ($dir_contents as $file) {
    $file_type = strtolower(end(explode('.', $file)));

    if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
    echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
    }
}
}
Run Code Online (Sandbox Code Playgroud)

小智 8

为了保证订单不同,每次都要求您携带有关页面加载之间显示顺序的数据.但是,这不一定是您所需要的 - 如果您每次只是随机化订单,那么目录中的图像数量越多,您获得相同订单两次的可能性就越小.

您可以简单地使用shuffle()随机化数组的顺序:

$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');

if (file_exists($dir) == false) {
    echo 'Directory \'', $dir, '\' not found';
} else {
    $dir_contents = scandir($dir);
    shuffle($dir_contents);

    foreach ($dir_contents as $file) {
        $file_type = strtolower(end(explode('.', $file)));

        if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
            echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
        }
    }
}
Run Code Online (Sandbox Code Playgroud)