2013-12-22 107 views
0

嗨我創建了隨機的PHP圖像腳本,但它不起作用。它迴應鏈接,但不包含隨機變量。PHP隨機圖像腳本麻煩

$f_contents = file ("random1.txt", FILE_USE_INCLUDE_PATH); 
$link = $f_contents[array_rand ($f_contents)]; /*Line 6*/ 


echo '<a href="http://www.site.com/view.php?t='.$link.'"><img src="http://www.site.com/images/'.$link.'.jpg" /></a>'; 
echo "</center>"; 
+2

你有你的日誌文件中的任何錯誤/警告? –

+1

我們如何知道$ f_contents有任何內容? – Popnoodles

+0

你指的是什麼「隨機」變量?在你的代碼中只有兩個變量。 –

回答

2

PHP函數array_rand返回一個數組。所以,你需要改變這一點:

$link = $f_contents[array_rand($f_contents)]; /*Line 6*/ 

進入這個:

$link = $f_contents[array_rand($f_contents)[0]]; /*Line 6*/ 

或許這個代替:

$rand_value = array_rand($f_contents); 
$link = $f_contents[$rand_value[0]]; /*Line 6*/ 

我也建議防錯你的代碼是這樣的,始終檢查$f_contents是否有內容:

$f_contents = file ("random1.txt", FILE_USE_INCLUDE_PATH); 
if (!empty($f_contents)) { 
    $rand_value = array_rand($f_contents); 
    $link = $f_contents[$rand_value[0]]; /*Line 6*/ 

    echo '<a href="http://www.site.com/view.php?t='.$link.'"><img src="http://www.site.com/images/'.$link.'.jpg" /></a>'; 
    echo "</center>"; 
} 

編輯array_rand接受第二個參數連接到多少個隨機項返回。所以,如果你該值設置爲1那麼它會返回一個字符串,而不是一個數組,這樣的代碼是這樣的:

$f_contents = file ("random1.txt", FILE_USE_INCLUDE_PATH); 
if (!empty($f_contents)) { 
    $rand_value = array_rand($f_contents, 1); 
    $link = $f_contents[$rand_value]; /*Line 6*/ 

    echo '<a href="http://www.site.com/view.php?t='.$link.'"><img src="http://www.site.com/images/'.$link.'.jpg" /></a>'; 
    echo "</center>"; 
} 
+0

這工作感謝! – John

+1

您也可以將array_rand中的第二個參數設置爲1.「只選擇一個條目時,array_rand()返回隨機條目的鍵。」 – Popnoodles

+0

@popnoodles好的提示! – JakeGould