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

yipeiwu_com6年前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开发过程中常用函数收藏

1.打印数组函数 复制代码 代码如下: function _print($array) { echo ("<pre>"); print_r($array); echo ("&...

PHP与SQL注入攻击[二]

PHP与SQL注入攻击[二] Magic Quotes 上文提到,SQL注入主要是提交不安全的数据给数据库来达到攻击目的。为了防止SQL注 入攻击,PHP自带一个功能可以对输入...

PHP生成唯一订单号

在网上找了一番,发现这位同学的想法挺不错的,redtamo,具体的请稳步过去看看,我作简要概述,该方法用上了英文字母、年月日、Unix 时间戳和微秒数、随机数,重复的可能性大大降低,还是...

PHP中in_array函数使用的问题与解决办法

先介绍一下需求背景: 发票方式: 0=捐赠(不要问我为什么,历史原因) 1=对中寄送 2=索取 3=电子发票 现在要对用户提交的数据进行检测: php;auto-links:fals...

PHP中的浅复制与深复制的实例详解

PHP中的浅复制与深复制的实例详解 前言: 最近温习了一下Design Pattern方面的知识,在看到Prototype Pattern这一设计模式时,注意到其中涉及到一个浅复制与深复...