实现发红包02

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/rulaixiong/article/details/87721415
1. 生成红包代码
class Red
{
    /**
     * @var int 红包总金额
     */
    private $total;

    /**
     * @var int 红包个数
     */
    private $num;

    /**
     * @var float 红包最小额
     */
    private $min;

    public function __construct($total = 0, $num = 0, $min = 0.01)
    {
        $this->total = $total;
        $this->num = $num;
        $this->min = $min;
    }

    /**
     * 生成红包
     * @return array
     */
    private function createRandRedPacket()
    {
		$list = array_fill(0, $this->num, $this->min);
        $this->total -= $this->min * $this->num;
        while ($this->total > 0) {
            $index = rand(0, $this->num - 1);
            $seek = rand($this->min * 100, round($this->total / $this->num, 4) * 100) / 100;
            $list[$index] += round(min($seek, $this->total), 2);
            $this->total -= $seek;
        }
        shuffle($list);
        return $list;
    }

    /**
     * 获取红包列表
     * @return array
     */
    public function getRed()
    {
        return $this->createRandRedPacket();
    }
}
2. 调用红包代码
$red = new Red(10, 10);
$list = $red->getRed();
print_r($list);exit;
3. 生成红包效果
Array
(
    [0] => 0.72
    [1] => 1.09
    [2] => 0.88
    [3] => 1.47
    [4] => 0.82
    [5] => 0.59
    [6] => 1.14
    [7] => 0.91
    [8] => 0.53
    [9] => 1.85
)
展开阅读全文

没有更多推荐了,返回首页