编程语言
首页 > 编程语言> > php大转盘算法

php大转盘算法

作者:互联网

// 获取中间记录的id
function get_rand() {
$arr = [
'0'=>['id'=>1,'name'=>'test1','rand'=>0],
'1'=>['id'=>2,'name'=>'test2','rand'=>1],
'2'=>['id'=>3,'name'=>'test3','rand'=>2],
'3'=>['id'=>4,'name'=>'test4','rand'=>1],
'4'=>['id'=>5,'name'=>'test5','rand'=>2],
'5'=>['id'=>6,'name'=>'test6','rand'=>6]
];
$result = false;
$all_rand = 0;
foreach ($arr as $v) {
$all_rand +=$v['rand'];
}
foreach ($arr as $key=>$value) {
if ($value['rand']>0) {
$pro = $value['rand'];
$randNum = mt_rand(1,$all_rand);
if ($randNum<=$pro) {
$result = $value['id'];
break;
} else {
$all_rand -= $pro;
}
}
}
return $result;
}
echo get_rand();

标签:rand,arr,name,value,大转盘,算法,result,php,id
来源: https://www.cnblogs.com/lzp4510/p/14884159.html