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生成缩略图的类代码

<?php /** * 功能:生成缩略图 * 作者:phpox * 日期:Thu May 17 09:57:05 CST 2007 */ class CreatMiniature...

PHP 采集程序中常用的函数

复制代码 代码如下://获得当前的脚本网址 function get_php_url() { if(!empty($_SERVER[”REQUEST_URI”])) { $scriptN...

php数组函数序列 之array_count_values() 统计数组中所有值出现的次数函数

array_count_values()定义和用法 array_count_values() 函数用于统计数组中所有值出现的次数。 本函数返回一个数组,其元素的键名是原数组的值,键值是该...

PHP安全的URL字符串base64编码和解码

如果直接使用base64_encode和base64_decode方法的话,生成的字符串可能不适用URL地址。下面的方法可以解决该问题: URL安全的字符串编码: 复制代码 代码如下:...

PHP钩子实现方法解析

本文实例讲述了PHP钩子实现方法。分享给大家供大家参考,具体如下: PHP编程的钩子实现,示例讲解和解释它们的作用,写了一个样板的钩子实现 钩子是编程里一个常见的概念,非常的重要。它...