2012-06-28 126 views
4

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

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

谢谢!

+0

什么问题? – 2012-06-28 07:05:28

+0

我会从所有可能的数字组成的数组开始,并随机将数字提取到一个新的数组中,直到我有足够的空间。这样你永远不会重复。 – TheZ

+1

它不应该是$ index <= $ arraycount,它应该是$ index <10(或者你想要选择的图像的数量) –

回答

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 
1
  1. 将您的横幅ID放在数组中。每次都会出现使用Knuth shuffle
  2. 在HTML输出
0

发出第一个10一个简单的方法来解决这个问题将是创建一个数组来保存旗帜的比以前的列表中多次

  • 洗牌此阵显示它们。

    我没有读你的代码(对不起),但这里有一个基本的概念,这是可能的。

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