在一段数中随机不重复的数,下面用大乐透举例:前区不重复5个数,从1到35;后区不重复2个数,从1到12。
首先写一个公共方法,调用2次即可:
所以重点在随机不重复的数。下列代码中详细说明:
public function getRandNumber($start = 1, $end = 35, $length = 5){
//初始化变量为0
$count = 0;
//建一个新数组
$temp = array();
while ($count < $length) {
//在一定范围内随机生成一个数放入数组中
$temp[] = mt_rand($start, $end);
//$data = array_unique($temp);
//去除数组中的重复值用了“翻翻法”,就是用array_flip()把数组的key和value交换两次。这种做法比用 array_unique() 快得多。
$data = array_flip(array_flip($temp));
//将数组的数量存入变量count中
$count = count($data);
}
//为数组赋予新的键名
shuffle($data);
//数组转字符串
$str = implode(",", $data);
//替换掉逗号
$number = str_replace(',',' ', $str);
return $number;
}
public function in_total(){
$front_area = $this->getRandNumber(1,35,5);
$back_area = $this->getRandNumber(1,12,2);
$in_total = $front_area . ' + '.$back_area;
echo $in_total;
}
打印结果:23 10 4 22 7 + 7 2
用到了 随机函数mt_rand()和键值键名互换函数array_flip() 、函数shuffle() 、函数implode()、函数str_replace()。