博客列表 >随机红包和固定红包

随机红包和固定红包

王石磊的博客
王石磊的博客原创
2018年01月02日 16:59:03787浏览
<?php
//随机红包
/**
* $bonus_total 红包总金额
* $bonus_count红包个数
* $bonus_type红包类型 1拼手气红包 0普通红包
*/

function randBonus($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;
}

$bonus_items = randBonus(100, 3, 1);
var_dump($bonus_items);
var_dump(array_sum($bonus_items));
另一种
function sendRandBonus($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;
}


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议