2016-03-25 82 views
1

嗨我有此數組:刪除多維數組項目通過值在項目

Array 
(
    [qty] => 1 
    [id] => 2 
    [name] => sallate me gjera plot 
    [price] => 8 
    [category_id] => 25 
    [dish_name] => sallate me gjera plot 
    [dish_id] => 2 
    [dish_category_id] => 25 
    [dish_qty] => 1 
    [dish_price] => 8 
) 
Array 
(
    [qty] => 1 
    [id] => 1 
    [name] => sallate cezar 
    [price] => 12 
    [category_id] => 25 
    [dish_name] => sallate cezar 
    [dish_id] => 1 
    [dish_category_id] => 25 
    [dish_qty] => 1 
    [dish_price] => 12 
) 

而我正在試圖做的是dish_id來取消該項目。 這就是我打算做的目的是:

if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0) 
     { 
      foreach ($_SESSION["cart_products"] as $key =>$cart_itm) 
      { 
       if($cart_itm["dish_id"]==$removable_id) 
       { 
        unset($cart_itm[$key]); 
       } 
      } 
     } 

誰能告訴我我在做什麼worng..thanks:d

+1

變化'未設置($ cart_itm [$關鍵]);'to'unset($ _ SESSION [「cart_products」] [$ key])'並檢查 –

+0

這是非常感謝:D –

+0

對不起@Anant first d ay here..I'm習慣了這個:/ –

回答

1

其實你需要unset來自實際數組的數據是$_SESSION["cart_products"]而不是$cart_itm

因此改變unset($cart_itm[$key]);unset($_SESSION["cart_products"][$key])

1

你需要從$_SESSION["cart_products"]變量

if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0) 
    { 
     foreach ($_SESSION["cart_products"] as $key =>$cart_itm) 
     { 
      if($cart_itm["dish_id"]==$removable_id) 
      { 
       unset($_SESSION["cart_products"][$key]); 
      } 
     } 
    } 
來取消
1

作爲替代方案,可以使用array_filter()與anonimous功能:

$removable_id = 1; 

$_SESSION["cart_products"] = array_filter 
( 
    $_SESSION["cart_products"], 
    function($row) use($removable_id) 
    { 
     return $row['dish_id'] != $removable_id; 
    } 
); 

print_r($_SESSION["cart_products"]); 

會打印:

Array 
(
    [0] => Array 
     (
      [qty] => 1 
      [id] => 2 
      [name] => sallate me gjera plot 
      [price] => 8 
      [category_id] => 25 
      [dish_name] => sallate me gjera plot 
      [dish_id] => 2 
      [dish_category_id] => 25 
      [dish_qty] => 1 
      [dish_price] => 8 
     ) 

) 
+0

感謝所有的答案......今天學到了很多:D –