0

This is just a picture of the result I got. As you can see, item 4 can be added again and again. What I want in my shopping cart is that, for each color, item 4 can only be added once.

enter image description here

if( isset($_SESSION['cart']) ){

    ################## Do looping to check array cart if already has item with same id and color ##########################

    $i = 0; 
    $j = 1; // set to index [1] //
    $found = '';

    foreach( $_SESSION['cart'] as $cart ){

        ######## Check if product chosen already exist in the cart #######

        if( $cart[$i]['id'] == $new_product['id'] && $cart[$i]['color'] == $new_product['color'] ){

            $found = true; // Found existing item in the array cart //

        }
        else{
            $found = false;
            $j++; // No item found in array cart, increase to index [2] //
        }

        ####### If no same item is found in cart, add the new product to the cart array ###############



        $i++; // Increase array index to check second array and so on //
    }

    if(!$found){ // No item found in array cart, add item into cart //

        $_SESSION['cart'][$j]['id'] = $new_product['id'];
        $_SESSION['cart'][$j]['product_name'] = $new_product['product_name'];
        $_SESSION['cart'][$j]['discount'] = $new_product['discount'];
        $_SESSION['cart'][$j]['qty'] = $new_product['qty'];
        $_SESSION['cart'][$j]['color'] = $new_product['color'];
        $_SESSION['cart'][$j]['shipping_fee'] = $new_product['shipping_fee'];

    }

}

else{

    $_SESSION['cart'][0]['id'] = $product['id'];
    $_SESSION['cart'][0]['product_name'] = $product['product_name'];
    $_SESSION['cart'][0]['discount'] = $product['discount'];
    $_SESSION['cart'][0]['qty'] = $qty;
    $_SESSION['cart'][0]['color'] = $color;
    $_SESSION['cart'][0]['shipping_fee'] = $shipping_fee;

}

How could I have my codes changed?

1 Answer 1

0

try this ...

if($found){ // item found in array cart

    $_SESSION['cart'][0]['id'] = $product['id'];
    $_SESSION['cart'][0]['product_name'] = $product['product_name'];
    $_SESSION['cart'][0]['discount'] = $product['discount'];
    $_SESSION['cart'][0]['qty'] = $qty;
    $_SESSION['cart'][0]['color'] = $color;
    $_SESSION['cart'][0]['shipping_fee'] = $shipping_fee;   

    }

}

else{ // no item found

     $_SESSION['cart'][$j]['id'] = $new_product['id'];
        $_SESSION['cart'][$j]['product_name'] = $new_product['product_name'];
        $_SESSION['cart'][$j]['discount'] = $new_product['discount'];
        $_SESSION['cart'][$j]['qty'] = $new_product['qty'];
        $_SESSION['cart'][$j]['color'] = $new_product['color'];
        $_SESSION['cart'][$j]['shipping_fee'] = $new_product['shipping_fee'];

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.