//range 是将1到42 列成一个数组
$numbers = range (1,42);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$result = array_slice($numbers,0,3); print_r($result);
Method 2
<?php <!-- lang: php -->$numbers = range (1,20); <!-- lang: php -->srand ((float)microtime()*1000000); <!-- lang: php -->shuffle ($numbers); <!-- lang: php -->while (list (, $number) = each ($numbers)) { <!-- lang: php -->echo "$number "; <!-- lang: php -->} <!-- lang: php -->?>
Method 3
用PHP,在1-20间随机产生5个不重复的值,如何做
<?php <!-- lang: php --> function NoRand($begin=0,$end=20,$limit=5){ <!-- lang: php -->$rand_array=range($begin,$end); <!-- lang: php -->shuffle($rand_array);//调用现成的数组随机排列函数 <!-- lang: php --> return array_slice($rand_array,0,$limit);//截取前$limit个 <!-- lang: php --> } <!-- lang: php -->print_r(NoRand()); <!-- lang: php --> ?>
或者不shuffle的话
<?php <!-- lang: php -->$tmp=array(); <!-- lang: php -->while(count($tmp)<5){ <!-- lang: php -->$tmp[]=mt_rand(1,20); <!-- lang: php -->$tmp=array_unique($tmp); <!-- lang: php --> } <!-- lang: php --> print join(',',$tmp); <!-- lang: php --> ?>