- 相關(guān)推薦
php生成N個不重復(fù)的隨機數(shù)
生成N個不重復(fù)的隨機數(shù),如何在php中實現(xiàn)呢?本文分享的這例php代碼,可以實現(xiàn)隨機數(shù)的生成,生成多個不重復(fù)的隨機數(shù),有興趣的朋友參考下。
需要生成1-25之間的16個不重復(fù)的隨機數(shù),去填補。
思路:
將隨機數(shù)存入數(shù)組,再在數(shù)組中去除重復(fù)的值,即可生成一定數(shù)量的不重復(fù)隨機數(shù)。
例子:
復(fù)制代碼 代碼示例:
<?php
/*
* array unique_rand( int $min, int $max, int $num )
* 生成一定數(shù)量的不重復(fù)隨機數(shù)
* $min 和 $max: 指定隨機數(shù)的范圍
* $num: 指定生成數(shù)量
* site www.jbxue.com
*/
function unique_rand($min, $max, $num) {
$count = 0;
$return = array();
while ($count < $num) {
$return[] = mt_rand($min, $max);
$return = array_flip(array_flip($return));
$count = count($return);
}
shuffle($return);
return $return;
}
$arr = unique_rand(1, 25, 16);
sort($arr);
$result = '';
for($i=0; $i < count($arr);$i++)
{
$result .= $arr[$i].',';
}
$result = substr($result, 0, -1);
echo $result;
?>
運行結(jié)果:
2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24
說明:
生成隨機數(shù)時用了 mt_rand() 函數(shù)。這個函數(shù)生成隨機數(shù)的平均速度要比 rand() 快四倍。
去除數(shù)組中的重復(fù)值時用了“翻翻法”,就是用 array_flip() 把數(shù)組的 key 和 value 交換兩次。這種做法比用 array_unique() 快得多。
返回數(shù)組前,先使用 shuffle() 為數(shù)組賦予新的鍵名,保證鍵名是 0-n 連續(xù)的數(shù)字。
若不進行此步驟,可能在刪除重復(fù)值時造成鍵名不連續(xù),不利于遍歷。
【php生成N個不重復(fù)的隨機數(shù)】相關(guān)文章:
解讀php生成N個不重復(fù)的隨機數(shù)04-17
PHP產(chǎn)生不重復(fù)隨機數(shù)的方法06-15
JAVA生成隨機數(shù)組10個數(shù)字并求和05-04
在PHP中使用隨機數(shù)的三個步驟03-08
php獲取隨機數(shù)組列表的方法03-22
php防止表單重復(fù)提交的方法02-24
PHP生成PDF文件withFPDF05-08
PHP生成SiteMap文件的代碼03-05
PHP生成Excel報表的方法05-24