php 从一个数组中随机获取固定数据
2024-10-14 00:23:30
<?php /* *
* 通过一个标识,从一个数组中随机获取固定数据
* $arr 数组
* $num 获取的数量
* $time 随机固定标识值,一般用固定时间或者某个固定整型
* */
function getRandFixedData($arr, $num, $time = 0)
{
if(empty($arr)){
return $arr;
}
$time = abs($time); //获取绝对值,防止出现负数
//数组的个数
$listcount = count($arr);
/*if($listcount < $num){
//数组总数不能少于需要获取的数量
return [];
}*/
$num = $listcount < $num ? $listcount:$num;
//分成$num 个数组每一个数组是多少个元素
$parem = floor($listcount / $num);
//分成$num 个数组还余多少个元素
$paremm = $listcount % $num;
$start = 0;
$new_array = [];
for ($i = 0; $i < $num; $i++) {
$end = $i < $paremm ? $parem + 1 : $parem;
$new_array[$i] = array_slice($arr, $start, $end);
$start = $start + $end;
}
if($time%2 == 1){
//固定几率逆向排序
$new_array = array_reverse($new_array);
}
$result = [];
for ($j = 0; $j < $num; $j++) {
$increase_num = $time+$j;
$index = $increase_num % count($new_array[$j]);
if($increase_num%3 == 1){
//固定几率逆向排序
$new_array[$j] = array_reverse($new_array[$j]);
}
$result[] = $new_array[$j][$index];
} return $result;
} //使用方法
$time = isset($_GET['time'])?$_GET['time']:123456789;
$arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];
$test1 = getRandFixedData($arr,5,$time);
echo '<pre>';
print_r($test1); $data = [1,2];
foreach ($data as $k=>$v){
$test2 = getRandFixedData($arr,5,$time+$k);
echo '<pre>';
print_r($test2);
} die;
最新文章
- 《Entity Framework 6 Recipes》中文翻译系列 (9) -----第二章 实体数据建模基础之继承关系映射TPH
- Android 抽屉效果的导航菜单实现
- Android LogCat使用详解
- 事件类型: 错误 事件来源: Service Control Manager 事件种类: 无 事件 ID: 7000
- python之列表、字典的使用
- 查GDI对象泄露的利器:GDIView
- Make Things Move -- Javascript html5版(三)三角函数形式的动画
- TortoiseGit - pull request
- Rxjava observeOn()和subscribeOn()初探
- 最优化算法:BFGS算法全称和L-BFGS算法全称
- Debian安装fail2ban来防止扫描
- CSS3使用transition属性实现过渡效果
- extjs ajax 同步 及 confirm 确认提示框问题
- [转载]Javascript .then()这个方法是什么意思?
- es6generator
- P4609 [FJOI2016]建筑师
- 【Linux】 Ncures库的介绍与安装
- 使用kubectl创建部署
- textmate常用快捷键备忘
- 在recycler中写的布局不起作用