[PHP] 纯文本查看 复制代码 <?php
function getRand($proArr) {
$result = [];
foreach ($proArr as $key => $val) {
$arr[$key] = $val['v'];
}
// 概率数组的总概率
$proSum = array_sum($arr);
asort($arr);
// 概率数组循环
foreach ($arr as $k => $v) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $v) {
$result = $proArr[$k];
break;
} else {
$proSum -= $v;
}
}
return $result;
}
$arr = [
['id'=>1, 'name'=>'特等奖', 'v'=>1],
['id'=>2, 'name'=>'一等奖', 'v'=>5),
['id'=>3, 'name'=>'二等奖', 'v'=>10],
['id'=>4, 'name'=>'三等奖', 'v'=>12],
['id'=>5, 'name'=>'四等奖', 'v'=>22],
['id'=>6, 'name'=>'没中奖', 'v'=>50]
];
$result = [];
for($i=0; $i<10000; $i++) {
$rand = getRand($arr);
isset($result[$rand['name']])? $result[$rand['name']]+=1: $result[$rand['name']] = 1;
}
asort($result);
var_dump($result);
|