mercredi 21 février 2018

splicing multidimensional array with if condition

I am creating an e-commerce site and am trying to create a multidimensional array for the shopping cart. Items within this should be in the format of:

1 => array(
  'item_id' => string
  'quantity' => string
  'attribute' => string
)

(where attribute is a product option like colour)

If I add a new item to my cart that has the same product ID and the same attribute I want to just update the quantity of that item.

The problem seems to be with my if statement here if (($key == "item_id" && $value == $id_to_add) && ($key == "attribute" && $value == $attribute_to_add))

Before I added the second condition it was working fine (adding quantity for the product ID without checking the attribute ($key == "item_id" && $value == $id_to_add))

Now instead of updating the quantity of an item it adds the same item again as a new item in the array.

Any help with this would be greatly appreciated.

Here is the form HTML

<form id="add_to_cart" name="add_to_cart" method="post" action="product.php?id=<?php echo $product_id; ?>">
    <input type="hidden" name="product_id" id="product_id" value="<?php echo $product_id; ?>">
    <select name="attribute" id="attribute"><?php echo $attribute_list; ?></select>
    <input type="number" name="quantity" id="quantity" value="1">
    <input type="submit" name="add_button" id="add_button" value="Add to Shopping Cart">
</form>

Here is the PHP to parse the form:

if (isset($_POST['product_id'])) {
    $id_to_add = $_POST['product_id'];
    $attribute_to_add = $_POST['attribute'];
    $quantity_to_add = $_POST['quantity'];

    echo $id_to_add.'-'.$attribute_to_add;
    $wasFound = false;
    $i = 0;
    if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])<1) { 
        $_SESSION["cart_array"] = array(1 => array("item_id" => $id_to_add, "quantity" => $quantity_to_add, "attribute" => $attribute_to_add));
    } else {;
        foreach ($_SESSION["cart_array"] as $each_item) { 
            $i++;
            while (list($key, $value) = each($each_item)) {
                if (($key == "item_id" && $value == $id_to_add) && ($key == "attribute" && $value == $attribute_to_add)){
                    array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $id_to_add, "quantity" => $each_item['quantity']+$quantity_to_add, "attribute" => $attribute_to_add)));
                    $wasFound = true;
                }
            }
        }
        if ($wasFound == false) {
            array_push($_SESSION["cart_array"], array("item_id" => $product_id, "quantity" => $quantity_to_add, "attribute" => $attribute_to_add));
        }
    }
    var_dump ($_SESSION["cart_array"]);
}

Aucun commentaire:

Enregistrer un commentaire