您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php从数组中随机选择若干不重复元素的方法_PHP

2024/6/5 4:43:46发布22次查看
本文实例讲述了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         if($i             $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程序设计有所帮助。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product