PHP:如何从多维数组中删除元素?

时间:2009-11-10 17:04:13

标签: php

我有这个代码将新元素添加到多维数组:

$this->shopcart[] = array(productID => $productID, items => $items);

那么如何从这个数组中删除一个元素?我尝试了这段代码,但它不起作用:

public function RemoveItem($item)
{
    foreach($this->shopcart as $key)
    {
        if($key['productID'] == $item)
        {
            unset($this->shopcart[$key]);               
        }
    }
}

我收到此错误:

  • 警告 50 C:\ xampplite \ htdocs \ katrinelund \ classes \ TillRepository.php 中未设置的非法偏移类型<登记/>

2 个答案:

答案 0 :(得分:7)

public function RemoveItem($item)
{
        foreach($this->shopcart as $i => $key)
        {
                if($key['productID'] == $item)
                {
                        unset($this->shopcart[$i]);   
                        break;                        
                }
        }
}

这应该可以解决问题。

<强>更新

还有另一种方式:

if ( false !== $key = array_search($item, $this->shopcart) )
{
    unset($this->shopcart[$key];
}

答案 1 :(得分:2)

你没有枚举索引,而是枚举那里的值,要取消设置数组索引,你必须通过索引取消设置,而不是取值。

此外,如果你的数组索引实际上是productID,你可以完全消除循环:

public function RemoveItem($productID)
{
    if (isset($this->shopcart[$productID]))
    {
        unset($this->shopcart[$productID]);
    }
}

您的示例未显示如何向$this->shopcart添加项目,但根据项目的需要,这可能是也可能不是您的选项。 (即如果你需要在购物车中有相同产品的单独实例,则不会。)

相关问题