Home >Backend Development >PHP Tutorial >PHP code to randomly extract some elements from an array

PHP code to randomly extract some elements from an array

WBOY
WBOYOriginal
2016-07-25 09:03:391094browse
  1. /**

  2. * Randomly extract array elements
  3. * author: notuser
  4. * 2012-12-29
  5. */
  6. class getValues ​​{
  7. public function inputValue($inputArray) {
  8. $this->inputArray = $inputArray;
  9. }
  10. public function getValue($number) {
  11. $this->number = $number;
  12. for($i = 0; $i < $this->number; $i ++) {
  13. $index = rand ( 0, count ( $this->inputArray ) - 1 - $i );
  14. $getArray [$i] = $this->inputArray [$index];
  15. unset ( $this->inputArray [$index] );
  16. for($k = $index; $k < count ( $this->inputArray ) - 1; $k ++) {
  17. $this->inputArray [$k] = $this-> inputArray [$k + 1];
  18. }
  19. }
  20. //asort ( $getArray ); // Sort from small to large, modify as needed
  21. return $getArray;
  22. }
  23. }

  24. //Test code

  25. $keywords = array(
  26. "we",
  27. "you",
  28. "them"
  29. );
  30. $getValue=new getValues();
  31. $getValue->inputValue($keywords);
  32. $ key = $getValue->getValue(1);//Randomly extract an element from the array
  33. echo $key;
  34. ? >

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn