我有这个代码来添加新元素到多维数组:
$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)
我收到此错误:
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)