2014-08-28 40 views
0

我正在尋找一些幫助來搞清楚PHP中的這個循環。我正在從購物車中刪除商品,並且陣列數據存儲在$_session['products']的內部。我遇到的問題是試圖讓購物車一次刪除多個項目。此代碼在一次刪除一個項目時運行良好。對於多個項目,它有時會複製未刪除的項目或刪除所有項目,而不是所選項目。在會話變量中刪除數組的問題PHP

Array ( 
[0] => Array ([name] => Another Test 
       [code] => 8456885345 
       [qty] => 1 
       [price] => 893.98) 
[1] => Array ([name] => Another Test 2 
       [code] => 11134455     
       [qty] => 1 
       [price] => 3.12) 
) 


if(isset($_GET["removemp"]) && isset($_GET["return_url"]) && isset($_SESSION["products"])) 
    { 
     $product_code = $_GET["removemp"]; 
     $return_url  = $_GET["return_url"]; 

     $product_explode = explode(',', $product_code); 

     foreach($product_explode as $code) 
     { 
      foreach ($_SESSION["products"] as $cart_itm) 
      { 
       if($cart_itm["code"]!=$code){ 
        $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]); 
       } 

       $_SESSION["products"] = $product; 
      } 
     } 
    } 
+0

你並不需要遍歷數組以刪除元素。創建一個您應該保留的索引列表,並將其僅複製到更新向量中。 – fuesika 2014-08-28 07:20:40

+0

你想刪除?在你的代碼中沒有'unset()' – Ghost 2014-08-28 07:21:10

+2

我建議你使用產品id作爲'$ _SESSION ['products']'中每個主要元素的'key'。從那裏,你可以根據用戶輸入刪除你想要的數量,當然也可以使用'unset()' – Ghost 2014-08-28 07:25:16

回答

0

商店的產品ID的作爲會話車數組鍵,並通過存儲所期望的產品ID的作爲逗號分隔的列表(如上述的問題)在$_GET["removemp"] PARAM刪除的每個項目,例如:

// where the array key is the product ID 

     Array ( 
      [12] => Array ([name] => Another Test 
          [code] => 8456885345 
          [qty] => 1 
          [price] => 893.98) 
      [34] => Array ([name] => Another Test 2 
          [code] => 11134455     
          [qty] => 1 
          [price] => 3.12) 
      ) 




      if(isset($_GET["removemp"]) && isset($_GET["return_url"]) && isset($_SESSION["products"])) 
       { 
        $product_code = $_GET["removemp"]; 
        $return_url  = $_GET["return_url"]; 

        $product_explode = explode(',', $product_code); 

        foreach($product_explode as $code) 
        { 

        // and simply unset each cart array 

         unset($_SESSION["products"][$code]); 
        } 
       } 

使用產品ID作爲數組鍵設置數組:

$_SESSION["products"][$product_id] = array ( 'name' => 'Another Test', 
               'code' => 8456885345, 
               'qty' => 1, 
               'price' => 893.98); 
+0

這看起來可能很愚蠢,但我該如何手動設置數組鍵值,而不是將它們排序爲0,1,2,3等。 – Ravinos 2014-08-28 09:06:24

+0

就像這樣:'$ _SESSION [ 「產品」] [$ PRODUCT_ID] =陣列( '姓名'=> '另一測試', \t \t \t \t \t \t \t \t \t \t \t '代碼'=> 8456885345, \t \t \t \t \t \t \t \t \t \t \t '數量'=> 1, \t \t \t \t \t \t \t \t \t \t \t「價格」 => 893.98);' – 2014-08-28 09:11:37

+0

我還編輯了答案,包括數組鍵的設置... – 2014-08-28 09:16:21