首页 > 解决方案 > Laravel 购物车价格计算错误

问题描述

我为在 Laravel 购物写了一个购物车,但总价计算错误。我的 Cart.php 是:

<?php

namespace App;

class Cart {

    public $items;
    public $totalQty = 0;
    public $totalPrice = 0;

    public function __construct($oldCart)
    {
        if ($oldCart)
        {
            $this->items = $oldCart->items;
            $this->totalQty = $oldCart->totalQty;
            $this->totalPrice = $oldCart->totalPrice;
        }
    }

    public function add($item , $id,$width,$height,$order,$count)
    {
        $storedItem = [
            'id' =>$item->id,
            'order' => $order,
            'qty' => 0,
            'width' => $width,
            'height' => $height,
            'priceperunit' => $item->priceperunit,
            'price' => $item->price,
            'item' => $item
        ];

        if ($this->items)
        {
            if(array_key_exists($id, $this->items))
            {
                $storedItem = $this->items[$id];
            }
        }

        if ($count)
        {
            $storedItem['qty'] += $count;
        }
        else
        {
            $storedItem['qty']++;
        }

        if ($storedItem['order'])
        {
            $storedItem['price'] = $storedItem['width'] * $storedItem['height'] * $storedItem['priceperunit'] * $storedItem['qty'];
            $this->items[] = $storedItem;
        }
        else
        {
            $storedItem['price'] = $item->price * $storedItem['qty'];
            $this->items[$id] = $storedItem;
        }

        if ($count)
        {
            $this->totalQty += $count;
        }
        else
        {
            $this->totalQty++;
        }       

        $this->totalPrice += $storedItem['price'];
    }
}

当我只添加一个项目时,总数和数量还可以,但是当我添加第二个项目时,它会计算三倍,当我再次添加它时,它会计算四倍。

这是我的购物车物品:

{
    "items": {
        "172": {
        "id": 172,
        "qty": 2,
        "price": 160,
        "item": {
            "id": 172,
            "name": "R3-60",
            "desc": null,
            "price": "80",
            }
        }
    }
}

和我的购物车总数:

{
"totalPrice": 240,
"totalQty": 2
}

标签: phplaravelcartshopping-cart

解决方案


我认为您通过尝试计算添加项目的总数来使自己变得更加困难。大多数Php操作并不那么昂贵,所以我会在您需要时计算它们。

class Cart {

    public $items;

    public function totalPrice() {
        return array_sum(array_column($this->items, 'price'));
    }

    public function totalQty() {
        return array_sum(array_column($this->items, 'qty'));
    }
}

您的数据结构非常具有误导性,因为您的代码结合注释显示了一些不同的东西,这是处理此问题的另一种方法的想法。


推荐阅读