PHP实现随机红包

    //随机红包(总份数、最大金额、最小金额、总数)
    protected function random_redpaper($total, $max, $min, $sum){
        $sum = $sum * 100;
        //按分单位,后面全部用整数金额

        $users = array_fill(0, $total, $min);
        $left = $sum - $min * $total;

        //将剩余金额按rand(1, ceil($left/$total))每次进行随机分配, $left 小于50直接分配完成
        for(;$left > 0;){
            $amount = $left > 50 ? rand(1, ceil($left/$total)) : $left;
            $user_index = rand(0, $total-1);
            if($users[$user_index] + $amount > $max){
                $amount = $max - $users[$user_index];
                $users[$user_index] = $max;
            }else{
                $users[$user_index] += $amount;
            }
            $left -= $amount;
        }

        //恢复按元单位
        foreach($users as &$user){
            $user = $user/100;
        }
        return $users;
    }

发表回复

您的电子邮箱地址不会被公开。