php模拟微信红包

方式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)); 



有什么好的算法可以再下面给我留言.谢谢!欢迎提意见.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值