0

所有的作品都完美無缺,但是當購物車中有更多的物品時...以及任何物品的數量(列表中最後一個物品除外)被更改時,下面的代碼進入無限循環,我通過在其中放置print_r語句來驗證它。php foreach進入無限循環,數組存儲在會話中

即進入無限循環的代碼的一部分:

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.

這是在添加第1項時如何初始化數組。

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

如果需要其他任何細節,請讓我知道..

更新:假設有在購物車中的三個項目。而且我改變了第三項的數量。這行得通。 但是,如果我更改第二個項目的數量,腳本將達到最大執行時間,第二個和第三個項目會在購物車中無限重複。

+3

對正在循環的數組進行更改是一個非常糟糕的主意! – GordonM 2012-04-19 06:58:02

+0

我有一種感覺,它可能會影響for循環,如果我添加/刪除項目..但我只是更換循環內的項目..認爲它不應該成爲一個問題。 – 2012-04-19 07:06:16

+0

在循環到達結尾之前,您正在將這些項目添加到數組中。 – fragmentedreality 2012-04-19 07:06:25

回答

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

這仍然修改循環內的數組(但不酷),但它不會混淆索引。

+0

謝謝,我會試試看。 但我在這裏嘗試了原始代碼.. http://tinyurl.com/c5qh3ha 它確實按預期工作.. – 2012-04-19 07:11:46

+0

它確實工作:) 謝謝! – 2012-04-19 07:26:36