php从数组中随机选择若干不重复元素的方法
本文实例讲述了php从数组中随机选择若干不重复元素的方法。分享给大家供大家参考。具体实现方法如下:
<?php
/*
*$array=thearraytobefiltered
*$total=themaximumnumberofitemstoreturn
*$unique=whetherornottoremoveduplicatesbeforegettingarandomlist
*/
functionunique_array($array,$total,$unique=true){
$newArray=array();
if((bool)$unique){
$array=array_unique($array);
}
shuffle($array);
$length=count($array);
for($i=0;$i<$total;$i++){
if($i<$length){
$newArray[]=$array[$i];
}
}
return$newArray;
}
$phrases=array('HelloSailor','AcidTest','BearGarden','BotchAJob','DarkHorse',
'InTheRed','ManUp','PanOut','QuidProQuo','RubItIn','Turncoat',
'YesMan','AllWet','BagLady','BeanFeast','BigWig','BigWig','BearGarden'
,'AllWet','QuidProQuo','RubItIn');
print_r(unique_array($phrases,1));
//Returns1result
print_r(unique_array($phrases,5));
//Returns5uniqueresults
print_r(unique_array($phrases,5,false));
//Returns5results,butmayhaveduplicatesif
//thereareduplicatesinoriginalarray
print_r(unique_array($phrases,100));
//Returns100uniqueresults
print_r(unique_array($phrases,100,false));
//Returns100results,butmayhaveduplicatesif
//thereareduplicatesinoriginalarray
希望本文所述对大家的php程序设计有所帮助。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短