php模拟微信发红包

<?php

$options = getopt(null, ['amount:', 'count:']);
//红包总金额
$amount = (double) $options['amount'];
//红包个数
$count = (int) $options['count'];

//单个红包最小金额
$minRedpack = 0.01;// minRedpack >= 0.01

//红包个数应该大于0
if ($count <= 0) {
    echo "count should greater than 0\n";
    return false;
}

//判断单个红包金额是否满足最小金额
if ($amount / $count < $minRedpack) {
    echo "single redpack needs at least $ {$minRedpack}\n";
    return false;
}

//发红包
for ($i = 1; $i <= $count; $i++) {
    //剩余红包个数
    $leftCount = $count - $i;
    //当前可发的最大金额
    $maxRedpack = round( $amount - ( $leftCount * $minRedpack ), 2);
    //随机发放
    $redpack = ( $i == $count) ? $amount : mt_rand($minRedpack * 100, $maxRedpack * 100) / 100;
    //减扣红包总金额
    $amount = round( $amount - $redpack, 2);
    echo "person:{$i} redpack:{$redpack} amountLeft:{$amount}\n";
}

运行

php redpack.php –amount=100 –count=5

结果:
person:1 redpack:20.58 amountLeft:79.42
person:2 redpack:13.53 amountLeft:65.89
person:3 redpack:18.56 amountLeft:47.33
person:4 redpack:5.94 amountLeft:41.39
person:5 redpack:41.39 amountLeft:0

Post Navigation