【PHP】按照个商品金额,等比例分配优惠劵

小破孩
2025-03-13 / 0 评论 / 5 阅读 / 正在检测是否收录...
    /**
     * @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;
    }
0

评论

博主关闭了所有页面的评论