【问题标题】:Wrong calculation of price in shopping cart in LaravelLaravel 购物车价格计算错误
【发布时间】:2019-12-30 02:08:47
【问题描述】:

我为我在 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
}

【问题讨论】:

  • { "items": { "172": { "id": 172, "qty": 3, "price": 240, "item": { "id": 172, "name": "R3-60", "desc": null, "price": "80", } } } } 和总数是{ "totalPrice": 480, "totalQty": 3 }

标签: php laravel cart shopping-cart


【解决方案1】:

我认为您尝试计算添加项目的总数会使您自己变得更加困难。大多数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'));
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多