2009-11-10 68 views
1

我有这样的代码到新元素添加到一个多维数组:PHP:我如何从一个multidemision数组中删除一个元素?

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

让我怎么从这个数组中删除一个元素?我想这个代码,但它不工作:

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

我得到这个错误:

  • 警告:非法偏移类型在取消所有在C:\ Xampplite文件\ htdocs中\ katrinelund \类\ TillRepository.php线
+0

哪条线是50线? – 2009-11-10 17:05:51

+0

第一个代码示例可能会遗漏键周围的某些'-s'。 – erenon 2009-11-10 17:06:40

+0

@ ricebowl:它一定是未设定的。 – erenon 2009-11-10 17:07:37

回答

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]; 
} 
+0

Upvote为第一个例子。在第二个错字:!== insted of!===,而第二个更不可读;如果可能的话,不要使用它。 – erenon 2009-11-10 17:22:30

+0

这不是一个错字,请看http://www.php.net/manual/en/language.operators.comparison.php。可读性较差?那么,这取决于从编码器到编码器,我个人更喜欢它。 – 2009-11-10 17:30:34

+0

@David:我看不到任何东西!=== – erenon 2009-11-10 17:35:17

2

你不列举了指数,但值出现,来取消数组索引,你必须通过索引来取消它,而不是价值。

此外,如果你的数组索引实际上是产品ID,你可以完全消除回路:

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

您的例子并不告诉你如何将项目添加到$this->shopcart,但是这可能会或可能不会是一个根据您的项目的需要选项。 (即,如果你需要在购物车中有单独的相同产品的话)。

相关问题