这篇文章主要介绍了php从数组中随机选择若干不重复元素的方法,涉及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 resultprint_r(unique_array($phrases, 5));// returns 5 unique resultsprint_r(unique_array($phrases, 5, false));// returns 5 results, but may have duplicates if// there are duplicates in original arrayprint_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操作mysql数据库及session对话的方法
php正则匹配与替换回调内容标签的方法
php正则表达式验证email的方法
以上就是php随机从数组中抽取元素的方法的详细内容。