php 从一个数组中随机获取固定数据

时间:2023-03-08 17:16:55
<?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;