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 5.0对象模型深度探索之属性和方法

可以联用->,如果一个对象的属性包含了一个对象,你可以使用两个->运算符来得到内部对象的属性. 你甚至可以用双重引用的字符串来放置这些表达式. 下面的例子中,对象Ho...

php中批量替换文件名的实现代码

代码如下 复制代码 代码如下: $dir = 'D:\Program Files\resource\application\Skin\PNG\\';//注意这里的路径,最后要加两个\,第...

在Mac上编译安装PHP7的开发环境

在Mac上编译安装PHP7的开发环境

今天看到鸟哥发微博说php7 beta1测试版发布了,于是赶紧就去抢先下载,把自己的开发环境也升级到PHP7去,话不多少,下面就一起来搞起吧。。。 首先你得去官网下载php7 beta...

利用ThinkPHP内置的ThinkAjax实现异步传输技术的实现方法

准备工作: ① 首先要会使用ThinkPHP这个框架 ② 最好有些ajax的基础(可以去看下小飞的另外一篇博文:Ajax实时验证"用户名/邮箱等"是否已经存在) ③ 4个js文档(点此免...

php使用escapeshellarg时中文被过滤的解决方法

本文分析了php使用escapeshellarg时中文被过滤的解决方法。分享给大家供大家参考。具体如下: 一、问题: 同样的代码,发现通过 localhost/index.php 访问,...