php怎么實現(xiàn)數(shù)組隨機且不重復(fù)

發(fā)布時間:2024-03-23
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()也會受此影響。
上一個:tps5450ddar_(ti(德州儀器))tps5450ddar中文資料_價格_pdf
下一個:固態(tài)分區(qū)表類型mbr與guid,如何區(qū)分硬盤分區(qū)類型是mbr還是 guid

帝亞草的栽培與管理
婚禮跟拍器材要求 婚禮跟拍需要什么器材
市政工程監(jiān)理資料整理要求是什么?
德國雄克刀具夾頭er型號介紹(雄克刀具夾頭優(yōu)勢特點)
九款花茶養(yǎng)顏清腸胃
6s以舊換新怎么換,iphone6s可以以舊換新嗎去哪里換
外加劑固含量測定儀怎么測試-冠亞水分儀說明書-固含量分析儀標準
菜鳥驛站官網(wǎng)加盟費用(菜鳥驛站加盟申請網(wǎng)址)
臨沂彩禮錢一般給多少
低壓線路上帶電作業(yè)應(yīng)注意事項
十八禁 网站在线观看免费视频_2020av天堂网_一 级 黄 色 片免费网站_绝顶高潮合集Videos