anulik anulik - 1 month ago 7
PHP Question

Increment Shopping cart item quantity using session

I know that my question could be very similar to anothers in Stackoverflow. I have found some similar questions but actually I couldn't get the right solution for my problem;

I am writing shopping cart using Sessions and ajax-json.
My products
structure is a bit complicated. It has name, size, type, colour and a
specific price for each type and size. The main point is that I can't
increment the item quantity if the name, size, type, color and price are
the same, if I'm adding the same product. Here is my code. I think I
am writing right, but I can't understand what is the problem.
Actually it increments the item quantity, but just one time, and when
I am checking the array, it's item quantity has not been incremented.

$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);

Answer

You need to increase quantity in your main product array like below.

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;
    }
}