2012-06-28 124 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']; 
        } 
    
    }