php - 从许多子文件夹中随机设置背景图像

标签 php css background-image

我试图从几个子文件夹中随机设置网页的背景图片,但图片名称相同。 例如: 邮件转发器可以是配置文件,然后是 mlhrs,然后是 RVS

在 (RVS) 文件夹中,您将拥有 x 编号或子文件夹,并且在每个子文件夹中,您将拥有 profile.jpg 图像

我的目标是每次重新加载页面时,图像从所有 (RVS) 子文件夹中随机更改

我该怎么做?

我找到这段代码,它几乎是我需要的,但我不知道如何更改为最佳方式:

你能帮帮我吗? 非常感谢

<!DOCTYPE HTML>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
        <title>404</title>
    </head>

    <body id="Background404">
        <p>404-Page not found. <a href="http://url.com">Home.</a></p>
    <?php
        $dir = './images';
        $fileNames = array();
        if(is_dir($dir)){
            $handle = opendir($dir);
            while(false !== ($file = readdir($handle))){
                if(is_file($dir.'/'.$file) && is_readable($dir.'/'.$file)){
                    $fileNames[] = $file;
                }
            }
            closedir($handle);
            $fileNames = array_reverse($fileNames);
            print_r($fileNames);
        }
        $totalLength = count($fileNames);
        $randInt = rand(0, $totalLength -1);
        $randFile = $fileNames[$randInt];
        echo $randFile;
        echo "<style> #Background404{background: url('./images/$randFile');}</style>";
    ?>

    </body>
</html>

最佳答案

随机使用shuffle

这里是解决方案代码

        $fileNames = shuffle($fileNames); // Shuffle All Array Files
        $randFile = end($fileNames); /*Get Last File Name Array (Last File Is Always Randomly, Becase We Did shuffle before get last element*/
        echo $randFile;
        echo "<style> #Background404{background: url('./images/$randFile');}</style>";````

关于php - 从许多子文件夹中随机设置背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57735416/

相关文章:

javascript - 双表不会提交第二表

php - 运行我自己的 OpenID 身份服务器/服务 (php)

html - CSS跨浏览器网页设计

html - 左右交替组中的 float 图像和文本在 div 的未知高度中垂直居中对齐

javascript - 更改html元素背景图像js

javascript - 自动点击加载更多但自动点击仅在第一次手动点击后触发

php - 如何重新映射数组以将其保存到夫妇

iphone - 带有背景图像的 UIViewController

html - 背景中的 Font Awesome 奇怪的颜色

c++ - 使用样式表不显示 QT 背景图像