【问题标题】:random number generation without duplicates无重复的随机数生成
【发布时间】:2012-06-29 16:09:39
【问题描述】:

我必须在网页中显示一些横幅。横幅的数量将是 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 个横幅。(一些横幅将来自同一个文件夹)。每次显示网页时,我都需要避免重复的横幅。

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

谢谢!

【问题讨论】:

  • 我会从一个包含所有可能数字的数组开始,然后将数字随机提取到一个新数组中,直到我受够了。这样你就不会重复了。
  • 不应该是$index

标签: php arrays random srand


【解决方案1】:

您可以从循环中的 $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

【讨论】:

    【解决方案2】:
    1. 将您的横幅 ID 放在一个数组中。每个都会发生一次
    2. 使用Knuth shuffle 对该数组进行洗牌
    3. 在 HTML 输出中发出前 10 个

    【讨论】:

      【解决方案3】:

      解决这个问题的一个简单方法是创建一个数组来保存横幅列表,而不是在显示它们之前。

      我没有阅读您的代码(抱歉),但这里有一个基本概念,这是可能的。

      $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'];
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-22
        • 2014-01-11
        • 2018-06-25
        • 1970-01-01
        • 2014-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多