php从数组中随机选择若干不重复元素的方法
程序员文章站
2022-05-25 14:31:14
本文实例讲述了php从数组中随机选择若干不重复元素的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
本文实例讲述了php从数组中随机选择若干不重复元素的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
<?php
/*
* $array = the array to be filtered
* $total = the maximum number of items to return
* $unique = whether or not to remove duplicates before getting a random list
*/
function unique_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('hello sailor','acid test','bear garden','botch a job','dark horse',
'in the red','man up','pan out','quid pro quo','rub it in','turncoat',
'yes man','all wet','bag lady','bean feast','big wig', 'big wig','bear garden'
,'all wet','quid pro quo','rub it in');
print_r(unique_array($phrases, 1));
// returns 1 result
print_r(unique_array($phrases, 5));
// returns 5 unique results
print_r(unique_array($phrases, 5, false));
// returns 5 results, but may have duplicates if
// there are duplicates in original array
print_r(unique_array($phrases, 100));
// returns 100 unique results
print_r(unique_array($phrases, 100, false));
// returns 100 results, but may have duplicates if
// there are duplicates in original array
/*
* $array = the array to be filtered
* $total = the maximum number of items to return
* $unique = whether or not to remove duplicates before getting a random list
*/
function unique_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('hello sailor','acid test','bear garden','botch a job','dark horse',
'in the red','man up','pan out','quid pro quo','rub it in','turncoat',
'yes man','all wet','bag lady','bean feast','big wig', 'big wig','bear garden'
,'all wet','quid pro quo','rub it in');
print_r(unique_array($phrases, 1));
// returns 1 result
print_r(unique_array($phrases, 5));
// returns 5 unique results
print_r(unique_array($phrases, 5, false));
// returns 5 results, but may have duplicates if
// there are duplicates in original array
print_r(unique_array($phrases, 100));
// returns 100 unique results
print_r(unique_array($phrases, 100, false));
// returns 100 results, but may have duplicates if
// there are duplicates in original array
希望本文所述对大家的php程序设计有所帮助。
上一篇: 智能机器人来了!究竟是喜还是忧?
下一篇: 面试经验分享(面试要主动)