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程序设计有所帮助。