php實現(xiàn)數(shù)組隨機且不重復(fù)的方法:首先創(chuàng)建一個php示例文件;然后利用“array_flip()”函數(shù)將數(shù)組的鍵和值翻轉(zhuǎn);接著利用php數(shù)組特性,覆蓋重復(fù)的鍵并再翻轉(zhuǎn)一次;最后去掉重復(fù)的值即可。
推薦:《php視頻教程》
下面寫幾種生成不重復(fù)隨機數(shù)的方法,直接上代碼吧
<?phpdefine('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); //隨機打亂數(shù)組 $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()更好更快的隨機函數(shù) $result = array_unique($result); //刪除數(shù)組中重復(fù)的元素 } return $result;}function rand3() { $result = array(); while(count($result) < count) { $_tmp = mt_rand(1, random_max); if(!in_array($_tmp, $result)) { //當數(shù)組中不存在相同的元素時,才允許插入 $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將數(shù)組的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()將數(shù)組的鍵和值翻轉(zhuǎn),利用php數(shù)組特性,重復(fù)的鍵會覆蓋,此時再翻轉(zhuǎn)一次,就相同于去掉了重復(fù)的值。
以上幾種方法只是簡單的例子,有的方法適用范圍有限。
在看看幾種方法的效率:
用array_unique()在數(shù)組較大時性能比較差,當然shuffle()也會受此影響。