2009-11-10 69 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,但是這可能會或可能不會是一個根據您的項目的需要選項。 (即,如果你需要在購物車中有單獨的相同產品的話)。

相關問題