2011-11-26 81 views
-2

我正在使用php腳本隨機顯示圖像。我重複了這個腳本三次,因爲我想一次顯示三張隨機圖像 - 我不確定如何更改php代碼以顯示3張圖像。PHP隨機設置的圖像

問題是,我不想碰到所有三個腳本一次顯示相同圖像的機會。有什麼我可以添加到此代碼,以確保每個圖像顯示總是不同?

<?php 
$random = "random.txt"; 
$fp = file($random); 
srand((double)microtime()*1000000); 
$rl = $fp[array_rand($fp)]; 
echo $rl; 
?> 

的HTML:

<?php include("rotate.php"); ?> 
<?php include("rotate.php"); ?> 
<?php include("rotate.php"); ?> 

*的random.txt只是有鏈接的文件名列表。

+0

@micha哪個論壇? o.O – tekknolagi

+1

google'$ random =「random.txt」; $ fp = file($ random);函數srand((雙)microtime中()* 1000000); $ rl = $ fp [array_rand($ fp)]; echo $ rl; ' – noob

回答

1

您可以使用array_rand()同時選擇多個隨機密鑰,就像這樣:

$random = "random.txt"; 
$fp = file($random); 
shuffle($fp); 
// You don't need this. The array_rand() function 
// is automatically seeded as of 4.2.0 
// srand((double)microtime()*1000000); 
$keys = array_rand($fp, 3); 
for ($i = 0; $i < 3; $i++): 
    $rl = $fp[$keys[$i]]; 
    echo $rl; 
endfor; 

這將消除包括文件不必多次。它可以一次完成。

+0

謝謝堆!我真的很喜歡,我不需要包含文件三次! :d – Jess

1

你可以編寫一個遞歸函數來檢查數組ID是否已經打印,如果已經打印了,再次調用它自己。只是把它放在for循環中打印三次:)

雖然請記住,真正的random圖像可能會重疊!

$beenDisplayed = array(); 

function dispRand($id) { 
    if (in_array($id, $beenDisplayed)) { 
     //generate random number 
     dispRand($id); 
    } 
    else { 
     array_push($beenDisplayed, $id); 
    } 
} 

for ($i = 0; $i < 3; $i++) { 
    dispRand($random_id); 
} 
+0

遞歸函數似乎有點過於複雜這個任務 – Galen

+0

@Galen也許,但我從來沒有聽說過'shuffle':P – tekknolagi

5

簡單的解決方案...

  1. 獲取隨機圖像陣列(你已經這樣做)
  2. 洗牌陣列
  3. 彈出圖像關閉陣列結束時,你需要一個

rotate.php

$random = "random.txt"; 
$fp = file($random); 
shuffle($fb); //randomize the images 
在你的代碼

<?php include('rotate.php') ?> 

每當你需要的圖像

<?php echo array_pop($fb) ?> 

http://php.net/manual/en/function.array-pop.php

+0

這是好的...太好... :) – tekknolagi

2
function GetRandomItems($arr, $count) 
{ 
    $result = array(); 
    $rcount = 0; 
    $arrsize = sizeof($arr); 
    for ($i = 0; ($i < $count) && ($i < $arrsize); $i++) { 
     $idx = mt_rand($rcount, $arrsize); 
     $result[$rcount] = trim($arr[$idx]); 
     $arr[$idx] = $arr[$rcount]; 
     $rcount++; 
    } 
    return $result; 
} 

$listname = "random.txt"; 
$list = file($listname); 
$random = GetRandomItems($list, 3); 
echo implode("<BR>", $list); 

附:其實,蓋倫的答案更好。出於某種原因,我忘了洗牌的xD