php – 无重复的随机数生成
发布时间:2020-12-13 22:44:17 所属栏目:PHP教程 来源:网络整理
导读:我必须在网页上显示一些横幅.横幅数量将在10(最多10).我可以在数据库中设置横幅和每个横幅文件夹的数量.横幅图像根据类别存储在单独的服务器文件夹中.横幅显示在列中. 我的代码是, 这里,long1,long2,… long10是数据库中的目录名 $array=array(); for($n=1;$
我必须在网页上显示一些横幅.横幅数量将在10(最多10).我可以在数据库中设置横幅和每个横幅文件夹的数量.横幅图像根据类别存储在单独的服务器文件夹中.横幅显示在列中.
我的代码是, $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=""/> } 例如:如果在数据库中设置了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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |