Zen*_*die 5 php arrays random srand
我必须在网页上显示一些横幅。横幅的数量将为10个(最多10个)。我可以设置横幅的数量和数据库中每个横幅的文件夹。标语图像根据类别存储在单独的服务器文件夹中。横幅显示在列中。
我的代码是,这里long1,long2,... long10是数据库中的目录名称
$array=array();
for($n=1;$n<=$long;$n++)
{
$files = array();
$dir=${'long'.$n};
if(is_dir($dir))
{
$openDir = opendir($dir);
while (false !== ($file = readdir($openDir)))
{
if ($file != "." && $file != "..")
{
$files[] = $file;
}
}
closedir($openDir);
}
mt_srand((double) microtime()*1000000);
$randnum = mt_rand(0,(sizeof($files)-1));
$arraycount=count($array);
for($index=0;$index<=$arraycount;$index++)
{
if(!in_array($array,$randnum))
{
$array[]=$randnum;
}
}
$img = $dir."/".$files[$randnum];
<input type="image" class="advt_image" src="<?=$img;?>" alt="" name=""/>
}
Run Code Online (Sandbox Code Playgroud)
例如:如果数据库中设置了7个横幅,则必须显示来自不同或相同文件夹的7个横幅(某些横幅将来自同一文件夹)。每次显示网页时,我都需要避免重复的横幅。
我已经分配了一个数组来存储每个随机数。我需要更改代码中的任何内容吗?有什么想法/想法吗?
谢谢!
您可以删除循环中 $files 数组中显示的图像。这意味着您还必须检查循环中数组的长度。你可以用array_diff这个。
$files = array(...); // this holds the files in the directory
$banners = array(); // this will hold the files to display
$count = 7;
for($i=0;$i<$count;$i++) {
$c = mt_rand(0,count($files));
$banners[] = $files[$c];
$files = array_diff($files, array($files[$c]));
}
// now go ahead and display the $banners
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1575 次 |
| 最近记录: |