php生成不重复随机数、数组的4种方法分享

yipeiwu_com6年前PHP代码库

下面写几种生成不重复随机数的方法,直接上代码吧

复制代码 代码如下:

<?php
define('RANDOM_MAX', 100);
define('COUNT', 10);

echo 'max random num: '.RANDOM_MAX, ' ;result count:'.COUNT, '<br/>';

invoke_entry('rand1');
invoke_entry('rand2');
invoke_entry('rand3');
invoke_entry('rand4');

function invoke_entry($func_name) {
 $time = new time();
 $time->time_start();
 call_user_func($func_name);
 echo $func_name.' time spend: ', $time->time_spend();
 echo '<br/>';
}
function rand1() {
 $numbers = range (1, RANDOM_MAX);
 shuffle($numbers); //随机打乱数组
 $result = array_slice($numbers, 1, COUNT);
 return $result;
}
function rand2() {
 $result = array();
 while(count($result)< COUNT) {
  $result[] = mt_rand(1, RANDOM_MAX); //mt_rand()是比rand()更好更快的随机函数
  $result = array_unique($result); //删除数组中重复的元素
 }
 return $result;
}
function rand3() {
 $result = array();  
 while(count($result) < COUNT) {
  $_tmp = mt_rand(1, RANDOM_MAX);
  if(!in_array($_tmp, $result)) { //当数组中不存在相同的元素时,才允许插入
   $result[] = $_tmp;
  }
 }  
 return $result;
}
function rand4() {
 $result = array();
 while (count($result) < COUNT) {
  $result[] = mt_rand(1, RANDOM_MAX);
  $result = array_flip(array_flip($result)); //array_flip将数组的key和value交换
 }
 return $result;
}
class time {
 private $_start;
 
 public function time_start() {
  $this->_start = $this->microtime_float();
 }
 public function time_spend() {
  return $this->microtime_float() - $this->_start;
 }
 private function microtime_float() {
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
 }
}


?>

 说一下第四种方法,就是翻翻法了,利用array_flip()将数组的键和值翻转,利用php数组特性,重复的键会覆盖,此时再翻转一次,就相同于去掉了重复的值。
以上几种方法只是简单的例子,有的方法适用范围有限。

在看看几种方法的效率:

用array_unique()在数组较大时性能比较差,当然shuffle()也会受此影响。

相关文章

php 网址url转迅雷thunder资源下载地址的方法函数

其实迅雷的地址就是:原url前面带AA,后面带ZZ之后再base64_encode编码即可即:  thunder:// + base64_encode("AA" +&nb...

php设计模式 Proxy (代理模式)

代理,指的就是一个角色代表另一个角色采取行动,就象生活中,一个红酒厂商,是不会直接把红酒零售客户的,都是通过代理来完成他的销售业务。而客户,也不用为了喝红酒而到处找工厂,他只要找到厂商在...

PHP删除HTMl标签的三种解决方法

方法1:直接取出想要取出的标记复制代码 代码如下:<?php    //取出br标记    function strip...

如何使用PHP往windows中添加用户

方法有一:   因为添加用户,所以你运行PHP程序的用户必须是管理员权限(Administrator),并且同时需要你的php.ini中的安全模式没有打开,并且关闭函...

php抓取页面的几种方法详解

在 做一些天气预报或者RSS订阅的程序时,往往需要抓取非本地文件,一般情况下都是利用php模拟浏览器的访问,通过http请求访问url地址, 然后得到html源代码或者xml数据,得到数...