문제

All works perfectly, but when there are more one items in the cart.. and the the quantity of any item (except the last item in list) is changed the code below goes into infinite loop, i have verified it by placing print_r statements in it.

The part of the code that goes into infinite loop:

if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
    // execute some code
    $item_to_adjust = $_POST['item_to_adjust'];
    $quantity = $_POST['quantity'];
    $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers
    if ($quantity >= 100) { $quantity = 99; }
    if ($quantity < 1) { $quantity = 1; }
    if ($quantity == "") { $quantity = 1; }
    $i = 0;
    foreach ($_SESSION["cart_array"] as $each_item) { 
              print_r($each_item);
              $i++;
              while (list($key, $value) = each($each_item)) {
                  if ($key == "item_id" && $value == $item_to_adjust) {
                      // That item is in cart already so let's adjust its quantity using array_splice()
                      array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
                  } // close if condition
              } // close while loop
    } // close foreach loop
}

P.S.

This is how the array is initialized when 1st item is added.

$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));

If any other detail is required please let me know..

Update : Suppose there are three items in in a cart. And i change the quantity of the 3rd item. It work. But if i change the quantity of the 2nd item, The script hits max execution time and the 2nd and 3rd items are repeated in the cart infinitely.

도움이 되었습니까?

해결책

foreach ($_SESSION["cart_array"] as $item_key => $each_item) {
    if ($item_to_adjust == $each_item["item_id"]) {
        $_SESSION["cart_array"][$item_key]["quantity"] = $quantity;
    }
}

This is still modifying the array inside the loop (not cool), but it does not mess with indexes.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top