Reputation: 131
I want to increase the quantity of product when i click on add to cart multiple time but i does not increase its quantity remain same, someone help me to solve this problem. what do i code in blank else section
if(isset($_POST["submit1"]))
{
if(isset($_SESSION["shopping_cart"]))
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
if(!in_array($_GET["product_id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["product_id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"],
'item_image' => $_POST["hidden_image"],
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
}
}
else
{
$item_array = array(
'item_id' => $_GET["product_id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"],
'item_image' => $_POST["hidden_image"],
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
Upvotes: 0
Views: 1087
Reputation: 369
You can get the key of an item with array_search
like this:
// look for 'item_id' with the value of $_GET["product_id"] inside of the cart
$itemIds = array_column( $_SESSION["shopping_cart"], "item_id" );
$key = array_search( $_GET["product_id"], $itemIds );
and then you can easily update that item's quantity by doing something like this:
...
if (isset($_SESSION["shopping_cart"]))
{
// look for 'item_id' with the value of $_GET["product_id"] inside of the cart
$itemIds = array_column( $_SESSION["shopping_cart"], "item_id" );
$key = array_search( $_GET["product_id"], $itemIds );
if ( $key === false )
{
$item_array = array(
'item_id' => $_GET["product_id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"],
'item_image' => $_POST["hidden_image"],
);
$_SESSION["shopping_cart"][] = $item_array;
}
else
{
// if quantity is invalid do something, else
$_SESSION["shopping_cart"][$key]["item_quantity"] += $_POST["quantity"];
}
}
...
Upvotes: 1
Reputation: 1
Your program logic is correct, just update it to:
$count++;
$_SESSION["shopping_cart"][$count] = $item_array;
Upvotes: 0