/**
* @Author:小破孩
* @Email:3584685883@qq.com
* @Time:2024/11/23 11:41
* @param $products ['id' => 'price','id' => price]
* @param $totalCouponAmount 优惠劵优惠金额
* @return array
* @Description:按照商品比例拆分优惠劵,分配给对应的商品
*/
public function getSplitCoupon($products, $totalCouponAmount) {
$totalAmount = array_sum($products);
$discounts = [];
$allocatedDiscount = 0;
foreach ($products as $id => $amount) {
$ratio = $amount / $totalAmount;
$discount = $ratio * $totalCouponAmount;
$roundedDiscount = round($discount, 2);
$discounts[$id] = $roundedDiscount;
$allocatedDiscount += $roundedDiscount;
}
// 调整以使总和为指定的优惠券总额
$diff = $totalCouponAmount - $allocatedDiscount;
if ($diff!= 0) {
$sortedDiscounts = $discounts;
arsort($sortedDiscounts);
$i = 0;
foreach ($sortedDiscounts as $id => $discount) {
if ($i < abs($diff)) {
$discounts[$id] += ($diff > 0)? 0.01 : -0.01;
}
$i++;
}
}
return $discounts;
}
版权属于:
小破孩
作品采用:
《
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
》许可协议授权
评论