随机数生成没有重复

时间:2012-06-28 07:02:47

标签: 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=""/>
 }

例如:如果在数据库中设置了7个横幅,我必须显示来自不同或相同文件夹的7个横幅。(某些横幅将来自同一个文件夹)。每当我显示网页时,我都需要避免重复的横幅。

我已经分配了一个数组来存储每个随机数。我需要更改代码中的任何内容吗?任何想法/想法?

谢谢!

3 个答案:

答案 0 :(得分:1)

  1. 将您的横幅ID放在数组中。每个都会发生一次
  2. 使用Knuth shuffle
  3. 对此数组进行随机播放
  4. 在HTML输出中发出前10个

答案 1 :(得分:0)

解决此问题的一种简单方法是创建一个数组来保存横幅列表,而不是显示横幅列表。

我没有阅读你的代码(对不起),但这是一个基本概念,可以实现这一点。

$bannerList = array();

//Now, check if the list contains the banner before adding it
while($rows) { //your big list of banners

    if(!in_array($rows['bannerpath'])) {
        $bannerList[] = $rows['bannerpath'];
    }

}

答案 2 :(得分:0)

您可以删除循环中$ 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
相关问题