總結下微信紅包隨機函數
1 固定面額 即 輸入金額生成已知的固定金額
//total 紅包總金額
protected function randCoupon($total=30){
$denomination = array(10,5,3,2,1);//固定面額
$arr = array();
while ($total){
if(count($denomination)>0){
$index = rand(0,count($denomination)-1);//隨機抽取一個固定面額索引
$money = $denomination[$index];
if($money>$total) continue;
array_push($arr,$money);
$total = (int)$total - (int)$money;
if($total==1){
array_push($arr,$total);
break;
}
if($total<1) break;
foreach ($denomination as $k => $item){
if($total <= $item){
array_splice($denomination,$k,1);
}
}
}
}
shuffle($arr);//重新打亂數組
return $arr;
}
2 隨機金額 即輸入金額及紅包個數 然后生成一個隨機數組
//拆分數值生成若干個和等于該數值隨機值
public function randNum($total=200,$num=17) {
$min=0.01;//每個人最少能收到0.01元
for ($i=1;$i<$num;$i++) {
$safe_total = ($total - ($num-$i)*$min) / ($num-$i);//隨機安全上限
if($safe_total < 0.01) $safe_total = 0.01;
$money = mt_rand($min*100,$safe_total*100)/100;
$total = $total - $money;
$data[] = round($money,2);
}
$data[] = round($total,2);
shuffle($data);
return $data;
}
浙公網安備 33010602011771號