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

<?php
class getValues {
   function __construct($inputArray){
        $this->inputArray = $inputArray;
   }
    //该函数此处没用到
    public function inputValue($inputArray) {
        $this->inputArray = $inputArray;
    }
    public function getValue($number) {
        $this->number = $number;
        for($i = 0; $i < $this->number; $i ++) {
          $count = count ( $this->inputArray ) - 1 - $i;
          $index = rand ( 0, $count);
          $getArray [$i] = $this->inputArray [$index];
          $temp = $this->inputArray [$count];
          $this->inputArray [$count] = $this->inputArray [$index];
          $this->inputArray [$index] = $temp;
        }
        //asort ( $getArray ); // 从小到大排序,根据需要修改
        return $getArray;
    }
}

//测试代码
$keywords  = array(
        "我们",
        "你们",
        "他们"
);
$getValue=new getValues($keywords);
$key = $getValue->getValue(1);//从数组中随机抽取一个元素
?>

推荐一个自己业余时间开发的网盘搜索引擎,360盘搜www.360panso.com
原文地址:https://www.cnblogs.com/eczhou/p/2751254.html