如果不在意 key 的話,可以直接使用 ?array_unique 內(nèi)置函數(shù),如:

成都創(chuàng)新互聯(lián)主營(yíng)霍山網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,重慶APP開(kāi)發(fā),霍山h5重慶小程序開(kāi)發(fā)搭建,霍山網(wǎng)站營(yíng)銷(xiāo)推廣歡迎霍山等地區(qū)企業(yè)咨詢(xún)
?php
$arr?=?array(1,1,2,1,5,9,9,6,7,8,8);
$unique?=?array_unique($arr)
var_dump($unique);
/*
輸出
啟清array(7)?{
[0]=
int(1)
喊旁仿???[2]=
int(2)
鄭纖??????[4]=
int(5)
[5]=
int(9)
[7]=
int(6)
[8]=
int(7)
[9]=
int(8)
}
*/
建議平時(shí)多看看php官網(wǎng)的文檔,希望有幫助。
下面寫(xiě)幾種生成不重復(fù)隨機(jī)數(shù)的方法,直接上代碼吧
復(fù)制代碼
代碼如下:
?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); //隨機(jī)打亂數(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()更好更快的隨機(jī)函數(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))
{ //當(dāng)數(shù)組中不存在相同的元素時(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);
}
}
?
你要數(shù)旁代碼還是辯亂算法啊?
我就直接說(shuō)下大概算法好了
假設(shè)有個(gè)數(shù)組里面有10個(gè)數(shù)字
然后你來(lái)個(gè)循環(huán),10個(gè)數(shù)字10次也差不多了
for($i=0;$i10;$i++){
$a1=rand(0,9);//隨機(jī)0到9的數(shù)字的
$a2=rand(0,9);
/*
*其實(shí)就是調(diào)換2個(gè)數(shù)字
*/
$j=$array[$a1];
$array[$a1]=$array[$a2];
$array[$a2]=$j;
}
循環(huán)十次攜畢檔,基本都打亂了,你的打亂沒(méi)什么要求,所以這樣應(yīng)該符合要求了
array_unique函數(shù)可以去除態(tài)指滾逗陸重復(fù),例如你的語(yǔ)句帆余可以修改為:
$arr=array_unique(array(1,1,2,1,5,9,9,6,7,8,8));
exit(json_encode($arr));
分享題目:php數(shù)組值不能重復(fù)數(shù)據(jù) php中數(shù)組
文章地址:http://www.chinadenli.net/article26/ddpescg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、電子商務(wù)、關(guān)鍵詞優(yōu)化、網(wǎng)站建設(shè)、微信公眾號(hào)、網(wǎng)站收錄
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)