当前位置:Gxlcms > PHP教程 > 从数组中随机抽取一些元素的php代码

从数组中随机抽取一些元素的php代码

时间:2021-07-01 10:21:17 帮助过:12人阅读

  1. /**

  2. * 随机抽取数组元素
  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 ); // 从小到大排序,根据需要修改
  21. return $getArray;
  22. }
  23. }

  24. //测试代码

  25. $keywords = array(
  26. "我们",
  27. "你们",
  28. "他们"
  29. );
  30. $getValue=new getValues();
  31. $getValue->inputValue($keywords);
  32. $key = $getValue->getValue(1);//从数组中随机抽取一个元素
  33. echo $key;
  34. ?>

人气教程排行