簡體   English   中英

PHP Rand()無法正常工作會導致不同的rand()變量。

[英]PHP Rand() not working same result in different rand () variables..

我有以下代碼:

$im = glob($directory . "*.html");
$last = end($im );
$hongi= rand(2, $last);

這是行不通的,因為rand()期望參數2起作用,並且此參數是一個字符串。

是否有可能使rand()與可變參數一起使用?

在此先感謝您的幫助。

編輯:

更好地解釋以下代碼:

我有數千個文件,每個文件名都是一個數字。

我將這些文件的名稱提取到數組中。

我使用end()獲得了最后一個值。

使用$ hongi獲取介於“ 2”和數組最后一個值之間的隨機值。

因此,隨機值將永遠不會超過數組的最后一個值。

我有一個非常基本的錯誤,因為我得到了這樣的文件路徑:

../motor/sector1/1700140030012011011111900.html ../motor/sector1/17001400300120110111920.html ../motor/sector1/17001400300120110111111930.html ../motor/sector1/17001400300120110111950.html

所以我這樣做

$im = glob($directory . "*.html");
$last = end($im );
$numl = substr($last,24,-5);
$hongi= rand(2, $num1);

沒關系,但是我要這樣做:

 $hongi= rand(2, $num1);
 $hongi1= rand(2,$num1);
 $hongi2= rand(2, $num1);
$hongi3= rand(2, $num1);
 $hongi4= rand(2, $num1);

但是所有“ hongi”變量都是相同的結果。 為什么?

如果希望使用字符串進行隨機選擇,則需要將它們放入數組中並進行數組隨機播放。

shuffle($array_of_filenames);
echo $array_of_filenames[0];  

更多示例: http : //php.net/manual/en/function.shuffle.php

類型轉換可以幫助:

$hongi= rand(2, (int)$last);

如果要獲取隨機文件名,首先,您使用的rand()錯誤。 在最小和最大之間取2個整數。 您為max提供的值是文件路徑,而不是整數。 您需要$ im的count() ,並使用它:

$im = glob($directory . "*.html");
$last = count($im);
$hongi= rand(2, $last - 1); // -1 because arrays start at 0
$random_file = $im[$hongi];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM