在项目中按值删除多维数组项

时间:2016-03-25 10:28:48

标签: php arrays multidimensional-array

嘿伙计们我有这个阵列:

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]);
                }
            }
        }

任何人都可以告诉我我做了什么......谢谢:D

3 个答案:

答案 0 :(得分: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 :(得分:1)

实际上,您需要unset来自$_SESSION["cart_products"]而不是$cart_itm的实际数组的数据。

所以将unset($cart_itm[$key]);更改为unset($_SESSION["cart_products"][$key])

答案 2 :(得分:1)

作为替代方案,您可以将array_filter()与一个无穷无尽的函数一起使用:

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
        )

)

将打印:

using