1 <?php 2 $total=20;//红包总金额 3 $num=10;// 分成10个红包,支持10人随机领取 4 $min=0.01;//每个人最少能收到0.01元 5 $redpack = new redpack($total,$num,$min); 6 $jieguo = $redpack->getPack(); 7 foreach($jieguo as $key=>$val){ 8 $n = $key+1; 9 echo '第'.$n.'个红包:'.$val['money'].' 元,余额:'.$val['balance'].' 元<br>'; 10 } 11 12 class redpack{ 13 //总金额 14 private $total=0; 15 //红包数量 16 private $num=0; 17 //最小红包金额 18 private $min=0.01; 19 20 public function __construct($total,$num,$min) 21 { 22 $this->total = $total; 23 $this->num = $num; 24 $this->min = $min; 25 } 26 //红包结果 27 public function getPack() 28 { 29 $total = $this->total; 30 $num = $this->num; 31 $min = $this->min; 32 for ($i=1;$i<$num;$i++) 33 { 34 $safe_total=($total-($num-$i)*$min)/($num-$i);//随机安全上限 35 $money=mt_rand($min*100,$safe_total*100)/100; 36 $total=$total-$money; 37 //红包数据 38 $readPack[]= [ 39 'money'=>$money, 40 'balance'=>$total, 41 ]; 42 } 43 //最后一个红包,不用随机 44 $readPack[] = [ 45 'money'=>$money, 46 'balance'=>0, 47 ]; 48 //返回结果 49 return $readPack; 50 } 51 52 }