检查类似的会话变量,仅增加数量(如果存在)

I need to add items to my cart, so if I add one product of productid = 1, and then I add that same product of productid = 1, I need it to only increase the quantity of the item, and not add another session of that product.

I've tried the following:

foreach ($_SESSION['cart'] as $item) {
        if ($item['product_id'] == $part_id) {
            $quantity++;
        }
    }

But I need to know how to remove the previous added session for that product.

This is the code that I am using to add products to my cart currently, but the following just adds another product with the quantity 2, so I have:

// -- Cart -- //

Product : 1 Quantity : 1

Product : 1 Quantity : 2

// -- Cart -- //

Code:

foreach ($_SESSION['cart'] as $item) {
if ($item['product_id'] == $part_id) {
    $quantity++;
    }
}

$_SESSION['cart'][] = array(
    'product_id' => $part_id,
    'title' => $title,
    'price' => $price,
    'default_img' => $default_img,
    'quantity' => $quantity);

EDIT: My initial question on how to unset the previous session, but if I add the same product another time, the quantity stays at 2, meaning it unsets the previous session with quantity = 3, and just increments the quantity +1 meaning the quantity remains at 2.

You are dealing with an associative array. You have the key to the object you want to remove. I would unset it right after adding the quantity. Now you can push your next object with the updated quantity.

foreach ($_SESSION['cart'] as $item) {
        if ($item['product_id'] == $part_id) {
            $quantity++;
            $_SESSION['cart'][$part_id] == NULL //Add this
        }
    }

This worked for me :

$exists = false;
    foreach ($_SESSION['cart'] as $key => $item) {
        if ($item['product_id'] == $part_id) {
            $exists = true;
        }
    }
    if ($exists == true) {
        $_SESSION["cart"][$key]['quantity']++;
    }
    else{
    $_SESSION['cart'][] = array(
        'product_id' => $part_id,
        'title' => $title,
        'price' => $price,
        'default_img' => $default_img,
        'quantity' => $quantity);
    }