Jump to content
makamo66

Update shopping cart by adding quantities together if the same product is chosen

Recommended Posts

This is the code that I'm using for a shopping cart in order to update the quantity if the same product id is chosen. 

$cart_items is a two-dimensional session array composed of the id session array and the quantity session array. While looping through $cart_items, I create a temporary array $temp_array so that I can execute some logic on the array without changing the normal output. $temp_array is the $cart_items array without the last items which would be the $_REQUEST id and the $_REQUEST quantity. So the two $_REQUESTs are popped off with array_pop and then the remaining $_SESSIONs are compared to the $_REQUEST id with 

$j = array_search($_REQUEST["element_id_$i"], $temp_array);
$j is now the key that corresponds to the id in $temp_array where the $_REQUEST id has been found. 

if( $j==$temp_array[$i]) 

If $j is the key of the item in $temp_array, then the $_REQUEST is unset and the quantities for the item are added together. 

There are two problems with this code. First of all the var_dump of the $temp_array is always an empty array but I am expecting to get an array with just the last element popped off. Secondly, 
I get the error "Undefined offset" for the $i variable in this line of the code: if( $j==$temp_array[$i]) 
 

foreach($cart_items as $item) {
foreach($item["id"] as $key => $val) {
foreach($item["quantity"] as $i => $value) {
    if ($key == $i){
    
$temp_array = $cart_items;
$array = array_pop($temp_array);
var_dump($temp_array);

if (isset($_REQUEST["element_id_$i"]) && isset($_REQUEST["quantity_$i"])&& isset($value)){
    
$j = array_search($_REQUEST["element_id_$i"], $temp_array);
if( $j==$temp_array[$i]) {
echo "<b>SAME PRODUCT ADDED</b>";
$value += $_REQUEST["quantity_$i"];
unset($_REQUEST["element_id_$i"]);
}}}}}}

 

Share this post


Link to post
Share on other sites

if you use the simple session cart definition that has been given on a different forum, using the item id as the array index, and storing the quantity as the array value under the index, doing what you are asking only takes a couple of lines of code.

  • Like 1

Share this post


Link to post
Share on other sites

It's in mac_gyver's post that you just replied to ...

14 hours ago, mac_gyver said:

using the item id as the array index, and storing the quantity as the array value under the index

Do you not bother to read replies?

Here's a sample script to illustrate the point

<?php
session_start();
$_SESSION['cart'] = $_SESSION['cart'] ?? [];

if ($_SERVER['REQUEST_METHOD']=='POST') {
    $post = array_map('trim', $_POST);
    if (!empty($post['productid']) && !empty($post['qty'])) {
        if (!isset($_SESSION['cart'][$_POST['productid']])) {
            $_SESSION['cart'][$_POST['productid']] = 0;
        }
        $_SESSION['cart'][$_POST['productid']] += $_POST['qty'];
    }
}

?>
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<style type="text/css">
    body     { font-family: verdana, arial, sans-serif; font-size: 11pt; }
    fieldset { width: 400px; padding: 8px; }
    legend   {background-color: #000; color: #FFF; padding: 4px; }
    label    { display: inline-block; width: 100px; }
</style>
</head>
<body>
<?= '<pre>Cart = ' . print_r($_SESSION['cart'], 1) . '</pre>' ?>
    <form method="post">
        <fieldset style='padding: 30px; width:400px;'>
        <legend>Add product to cart</legend>
            <label>Product</label> 
            <select name='productid' required>
               <option value=''>- Choose product -</option>
               <option value='PROD1'>Widget</option>
               <option value='PROD2'>Gizmo</option>
               <option value='PROD3'>Wotsit</option>
               <option value='PROD4'>Thingy</option>
            </select>
            <br><br>
            <label>Quantity</label> 
            <input type="number" name="qty" value="1" size="5" required>
            <br><br>
            <label></label> 
            <input type="submit" name="btnSub" value="Submit">
        </fieldset>
    </form>
</body>
</html>

Screenshot:

image.png.4edb39db7ade25c31d1d43e524c426ad.png

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.