我试图从几个子文件夹中随机设置网页的背景图片,但图片名称相同。 例如: 邮件转发器可以是配置文件,然后是 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/