php - 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
}
解决方案
我认为您通过尝试计算添加项目的总数来使自己变得更加困难。大多数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'));
}
}
您的数据结构非常具有误导性,因为您的代码结合注释显示了一些不同的东西,这是处理此问题的另一种方法的想法。
推荐阅读
- multithreading - Jboss logger 在线程生命周期中清除 MDC
- go - 无法使用 gopkg.in/yaml.v2 解组具有缩进或空值的 yaml 文件
- ios - 如何为动态 UICollectionView 制作自定大小的单元格?
- google-chrome-extension - 在 chrome.tabs.query 和 chrome.tabs.getcurrent 中,标签长度为零
- amazon-web-services - 如何从 terraform 启动产品
- javascript - 在 React 函数组件中未定义 contextType
- python - 在列表中连接多个数据帧
- scala - 如何获取scala特征中所有方法的名称
- java - 从锁定屏幕唤醒设备并显示活动
- html - 如何使用CSS删除内联元素底部和Div内边距之间的空白?