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

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

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

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

相关文章

通过PHP的内置函数,通过DES算法对数据加密和解密

由于项目的需要,要写一个能生成“授权码”的类(授权码主要包含项目使用的到期时间),生成的授权码将会写入到一个文件当中,每当项目运行的时候,会自动读取出文件中的密文,然后使用唯一的“密钥”...

攻克CakePHP系列二 表单数据显示

攻克CakePHP系列二 表单数据显示

首先建立数据库cake_ext,并执行如下sql文: CREATE TABLE `companies` (   `id` ...

php实现概率性随机抽奖代码

1、初始数据: 权重越大,抽取的几率越高 [奖品1, 权重 5], [ 奖品2, 权重6], [ 奖品3, 权重 7], [ 奖品4, 权重2] 2、处理步骤: 1)N = 5 +...

PHP实现压缩图片尺寸并转为jpg格式的方法示例

本文实例讲述了PHP实现压缩图片尺寸并转为jpg格式的方法。分享给大家供大家参考,具体如下: <?php function ImageToJPG($srcFile,$d...

PHP中的数组处理函数实例总结

本文实例总结了PHP中的数组处理函数。分享给大家供大家参考,具体如下: <?php //改变数组键的大小写 $arr1=array("a"=>"Lamp","...