Heim  >  Artikel  >  Backend-Entwicklung  >  PHP不重复随机数的生成方法_PHP教程

PHP不重复随机数的生成方法_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:33:33851Durchsuche

原理很简单,先写一个函数,生成0-z这36个字符中的一个。每次调用 getOptions() 方法生成一个字符,它们的存储如下:array[0] = 0, array[1] = 1, ……, array[35] = z。

Array ( 
	[0] => 0 
	[1] => 1 
	[2] => 2 
	[3] => 3 
	[4] => 4 
	[5] => 5 
	[6] => 6 
	[7] => 7 
	[8] => 8 
	[9] => 9 
	[10] => a 
	[11] => b 
	[12] => c 
	[13] => d 
	[14] => e 
	[15] => f 
	[16] => g 
	[17] => h 
	[18] => i 
	[19] => j 
	[20] => k 
	[21] => l 
	[22] => m 
	[23] => n 
	[24] => o 
	[25] => p 
	[26] => q 
	[27] => r 
	[28] => s 
	[29] => t 
	[30] => u 
	[31] => v 
	[32] => w 
	[33] => x 
	[34] => y 
	[35] => z 
)

然后在0-35之间随机生成一个数作为索引,其实就是在上面数组中随机取出一个数,作为变量 $result 中的第一个字符。这个随机索引随后会被赋值成数组最后一个,它将不会参与下一轮的随机选取。

<?php
// 生成0123456789abcdefghijklmnopqrstuvwxyz中的一个字符
function getOptions()
{
 	$options = array();
 	$result = array();
 	for($i=48; $i<=57; $i++)
 	{
     	array_push($options,chr($i));  
 	}
 	for($i=65; $i<=90; $i++)
  	{
      	$j = 32;
      	$small = $i + $j;
      	array_push($options,chr($small));
	}
 	return $options;
}
/*
$e = getOptions();
for($j=0; $j<150; $j++)
{
	echo $e[$j];
}
*/
$len = 10;
// 随机生成数组索引,从而实现随机数
for($j=0; $j<100; $j++)
{
 	$result = "";
 	$options = getOptions();
 	$lastIndex = 35;
 	while (strlen($result)<$len)
 	{
  		// 从0到35中随机取一个作为索引
		$index = rand(0,$lastIndex);
		// 将随机数赋给变量 $chr
  		$chr = $options[$index];
		// 随机数作为 $result 的一部分
  		$result .= $chr;
  		$lastIndex = $lastIndex-1;
		// 最后一个索引将不会参与下一次随机抽奖
  		$options[$index] = $options[$lastIndex];
 	}
 	echo $result."n";
}
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752456.htmlTechArticle原理很简单,先写一个函数,生成0-z这36个字符中的一个。每次调用 getOptions() 方法生成一个字符,它们的存储如下:array[0] = 0, array[1] = 1...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn