2014-08-28 49 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