方式1:
/** * [weixinRandBonus 模擬微信紅包] * @param integer $bonus_total [紅包總金額] * @param integer $bonus_count [紅包個數] * @param integer $bonus_type [紅包類型 1 手氣紅包 0 普通紅包] * @return [array] [返回紅包] */function weixinRandBonus($bonus_total=0, $bonus_count=3, $bonus_type=1){ $bonus_items = array(); // 建一個存儲紅包結果數組 $bonus_balance = $bonus_total; // 每次分完之后的余額 $bonus_avg = number_format($bonus_total/$bonus_count, 2); // 平均每個紅包多少錢 $i = 0; while($i<$bonus_count){ if($i<$bonus_count-1){ $rand = $bonus_type?(rand(1, $bonus_balance*100-1)/100):$bonus_avg; // 根據紅包類型計算當前紅包的金額 $bonus_items[] = $rand; $bonus_balance -= $rand; }else{ $bonus_items[] = $bonus_balance; // 最后一個紅包直接承包最后所有的金額,保證發出的總金額正確 } $i++; } return $bonus_items; }// 發3個拼手氣紅包,總金額是100元 $bonus_items = weixinRandBonus(100, 10, 1); // 查看生成的紅包 var_dump($bonus_items); // 校驗總金額是不是正確,看看微信有沒有坑我們的錢 var_dump(array_sum($bonus_items));方式2:
/** * [weixinSendRandBonus 模擬微信紅包] * @param integer $total [紅包總金額] * @param integer $count [紅包個數] * @param integer $type [紅包類型 1 手氣紅包 0 普通紅包] * @return [array] [返回紅包] */function weixinSendRandBonus($total=0, $count=3, $type=1){ if($type==1){ $input = range(0.01, $total, 0.01); if($count>1){ $rand_keys = (array) array_rand($input, $count-1); $last = 0; foreach($rand_keys as $i=>$key){ $current = $input[$key]-$last; $items[] = $current; $last = $input[$key]; } } $items[] = $total-array_sum($items); }else{ $avg = number_format($total/$count, 2); $i = 0; while($i<$count){ $items[] = $i<$count-1?$avg:($total-array_sum($items)); $i++; } } return $items; }運行:
// 發10個拼手氣紅包,總金額是100元 $bonus_items = weixinSendRandBonus(100, 10, 1); // 查看生成的紅包 var_dump($bonus_items); // 校驗總金額是不是正確,看看微信有沒有坑我們的錢 var_dump(array_sum($bonus_items));
有什么好的算法可以再下面給我留言.謝謝!歡迎提意見.
新聞熱點
疑難解答
圖片精選