PHP:如何从多重分裂数组中删除元素?

Pok*_*oku 1 php

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

$this->shopcart[] = array(productID => $productID, items => $items);
Run Code Online (Sandbox Code Playgroud)

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

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

我收到此错误:

  • 警告:第50行的C:\ xampplite\htdocs\katrinelund\classes\TillRepository.php中未设置非法偏移类型

Dav*_*dža 7

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

这应该够了吧.

更新

还有另一种方式:

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