class Coupon
{protected $amount;protected $num;protected $coupon_min;protected $items = [];public function __construct($amount, $num = 1, $coupon_min = 0.01){$this->amount = $amount;$this->num = $num;$this->coupon_min = $coupon_min;}public function handle(){if ($this->amount < $validAmount = $this->coupon_min * $this->num) {throw new Exception('红包总金额必须≥'.$validAmount.'元');}$this->apportion();return ['items' => $this->items,];}protected function apportion(){$num = $this->num; $amount = $this->amount; while ($num >= 1) {if ($num == 1) {$coupon_amount = $this->decimal_number($amount);} else {$avg_amount = $this->decimal_number($amount / $num); $coupon_amount = $this->decimal_number($this->calcCouponAmount($avg_amount, $amount, $num));}$this->items[] = $coupon_amount; $amount -= $coupon_amount;--$num;}shuffle($this->items); }protected function calcCouponAmount($avg_amount, $amount, $num){if ($avg_amount <= $this->coupon_min) {return $this->coupon_min;}$coupon_amount = $this->decimal_number($avg_amount * (1 + $this->apportionRandRatio()));if ($coupon_amount < $this->coupon_min|| $coupon_amount > $this->calcCouponAmountMax($amount, $num)) {return $this->calcCouponAmount($avg_amount, $amount, $num);}return $coupon_amount;}protected function calcCouponAmountMax($amount, $num){return $this->coupon_min + $amount - $num * $this->coupon_min;}protected function apportionRandRatio(){if (rand(1, 100) <= 60) {return rand(-70, 70) / 100; }return rand(-30, 30) / 100; }protected function decimal_number($amount){return sprintf('%01.2f', round($amount, 2));}
}
$coupon = new Coupon(200, 5, 30);
$res = $coupon->handle();
print_r($res);
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!