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 var_export与var_dump 输出的不同

问题发现在跟踪yratings_get_targets的时候,error_log(var_export(yblog_mspconfiginit("ratings"),true));老是打...

php中array_slice和array_splice函数解析

php中array_slice和array_splice函数解析

本文主要介绍了php中array_slice和array_splice函数,感兴趣的可以围观一下, array_slice和array_splice函数是用在取出数组的一段切片,arr...

PHP依赖注入容器知识点浅析

依赖注入容器理解 耦合 一个好的代码结构设计一定是松耦合的,这也是很多通用设计模式的宗旨,就是把分散在各处的同一个功能的代码汇聚到一起,形成一个模块,然后在不同模块之间通过一些细小的、明...

php中时间函数date及常用的时间计算

曾在项目中需要使用到今天,昨天,本周,本月,本季度,今年,上周上月,上季度等等时间戳,趁最近时间比较充足,因此计划对php的相关时间知识点进行总结学习 1,阅读php手册date函数 常...

php foreach 使用&amp;(与运算符)引用赋值要注意的问题

foreach 通过在 $value 之前加上 & 很容易就能修改数组的单元,如: PHP代码 复制代码 代码如下: foreach($arr as $value){ $value .=...