Skip to content

Instantly share code, notes, and snippets.

@sushengbuhuo
Created October 12, 2019 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sushengbuhuo/045c695c3a234794945f03e99a2bf199 to your computer and use it in GitHub Desktop.
Save sushengbuhuo/045c695c3a234794945f03e99a2bf199 to your computer and use it in GitHub Desktop.
抽奖功能
function get_rand($proArr) {
$res = '';
//改了数组的总概率精度
$proSum = array_sum($proArr);
//概率数组循环
foreach ($proArr as $k => $v) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $v) {
$res = $k;
break;
} else {
$proSum -= $v;
}
}
unset($proArr);
return $res;
}
$prize_arr = [
0 => [
'id' => 1,
'prize' => '平板电脑',
'v' => 1
],
1 => [
'id' => 2,
'prize' => '数码相机',
'v' => 5
],
2 => [
'id' => 3,
'prize' => '智能能手机',
'v' => 10
],
3 => [
'id' => 4,
'prize' => '数码相机',
'v' => 40
],
4 => [
'id' => 5,
'prize' => '谢谢惠顾',
'v' => 60
],
];
//实现抽奖功能
function setPrize($prize_arr) {
$arr = array();
$pr = array();
foreach ($prize_arr as $key => $val) {
$arr[$val['id']] = $val['v'];
}
$rid = get_rand($arr);
//中奖项
$res['yes'] = $prize_arr[$rid - 1]['prize'];
unset($prize_arr[$rid - 1]);
shuffle($prize_arr);
for ($i = 0; $i < count($prize_arr); $i++) {
$pr[] = $prize_arr[$i]['prize'];
}
$res['no'] = $pr;
echo json_encode($res, true);
}
setPrize($prize_arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment