0

我知道我的问题可能与 Stackoverflow 中的其他问题非常相似。我发现了一些类似的问题,但实际上我无法为我的问题找到正确的解决方案;

我正在使用 Sessions 和 ajax-json 编写购物车。我的产品结构有点复杂。它有名称、尺寸、类型、颜色和每种类型和尺寸的具体价格。要点是,如果我要添加相同的产品,如果名称、尺寸、类型、颜色和价格相同,我无法增加商品数量。这是我的代码。我认为我写得对,但我无法理解问题所在。实际上它增加了项目数量,但只是一次,当我检查数组时,它的项目数量没有增加。

$data = json_decode($_POST['jsonData'], true);
    $pr_type = $data['pr_type'];
    $pr_size = $data['pr_size'];
    $pr_link = $data['pr_link'];
    $pr_color = $data['pr_color'];
    $pr_price = $data['pr_price'];

    $products_s = $this->getSession()->get('prof_cart');
    $product = array();

    if (empty($products_s)) {
        $products_s = array();
    } else {
        $products_s = $products_s;
    }

    $products = Model::factory('Client_Product')->getProductById($pr_link);
    $type = Model::factory("Client_Product")->getProductTypeByLink($pr_type);
    $size = Model::factory("Client_Product")->getProductSizeById($pr_size);
    if ($pr_type != 'undefined') {
        $product['type'] = $type[0]['title'];
    } else {
        $product['type'] = "";
    }
    $isCreate = true;

    foreach ($products_s as $id) {
        if ($id['price'] == $pr_price &&
                $id['title'] == $products[0]['title'] &&
                $id['size'] == $size[0]['size'] &&
                $id['type'] == $type[0]['title']) {
            $id['quant']++;
            $isCreate = false;
        }
    }

    if ($isCreate) {
        $product['quant'] = 1;
        $product['size'] = $size[0]['size'];
        $product['title'] = $products[0]['title'];
        $product['price'] = $pr_price;            
        $product['color'] = $pr_color;
        array_push($products_s, $product);
    }

    $sum = 0;
    foreach ($products_s as $id) {
        $sum += $id['price'] * $id['quant'];
    }

    //echo $sum;

    echo "<pre>";
   var_dump($products_s);
   echo "</pre>";

    $this->getSession()->set('prof_cart', $products_s);

    $this->getSession()->set('prof_sum', $sum);
4

2 回答 2

1

您需要增加主要产品阵列中的数量,如下所示。

foreach ($products_s as $key => $id) {
    if ($id['price'] == $pr_price &&
            $id['title'] == $products[0]['title'] &&
            $id['size'] == $size[0]['size'] &&
            $id['type'] == $type[0]['title']) {
        $products_s[$key]['quant']++;
        $isCreate = false;
    }
}
于 2013-05-14T16:17:49.380 回答
0

尝试这个 :

    foreach ($products_s as $id) {
    if ($id['price'] == $pr_price &&
            $id['title'] == $products[0]['title'] &&
            $id['size'] == $size[0]['size'] &&
            $id['type'] == $type[0]['title']) {
        $id['quant'] = $id['quant']++;
        $isCreate = false;
    }
}
于 2013-05-14T16:21:07.457 回答