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

这篇文章主要介绍了php从数组中随机选择若干不重复元素的方法,涉及php数组操作的相关常用技巧,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了php从数组中随机选择若干不重复元素的方法,分享给大家供大家参考,具体实现方法如下:

  1. <?php
  2. /*
  3. * $array = the array to be filtered
  4. * $total = the maximum number of items to return
  5. * $unique = whether or not to remove duplicates before getting a random list
  6. */
  7. function unique_array($array, $total, $unique = true){
  8. $newArray = array();
  9. if((bool)$unique){
  10. $array = array_unique($array);
  11. }
  12. shuffle($array);
  13. $length = count($array);
  14. for($i = 0; $i < $total; $i++){
  15. if($i < $length){
  16. $newArray[] = $array[$i];
  17. }
  18. }
  19. return $newArray;
  20. }
  21. $phrases = array('Hello Sailor','Acid Test','Bear Garden','Botch A Job','Dark Horse',
  22. 'In The Red','Man Up','Pan Out','Quid Pro Quo','Rub It In','Turncoat',
  23. 'Yes Man','All Wet','Bag Lady','Bean Feast','Big Wig', 'Big Wig','Bear Garden'
  24. ,'All Wet','Quid Pro Quo','Rub It In');
  25. print_r(unique_array($phrases, 1));
  26. // Returns 1 result
  27. print_r(unique_array($phrases, 5));
  28. // Returns 5 unique results
  29. print_r(unique_array($phrases, 5, false));
  30. // Returns 5 results, but may have duplicates if
  31. // there are duplicates in original array
  32. print_r(unique_array($phrases, 100));
  33. // Returns 100 unique results
  34. print_r(unique_array($phrases, 100, false));
  35. // Returns 100 results, but may have duplicates if
  36. // there are duplicates in original array

希望本文所述对大家的php程序设计有所帮助。