2013-01-10 54 views
3

我有一個二維陣列並希望總是刪除/取消設置的最後一個數組項(在這種情況下數組[3])下面的代碼示例中,然後再將它放入SESSION中。
我仍然是一個PHP的新手,並嘗試以下沒有成功。
任何幫助將不勝感激。如何刪除最後一個數組項中的二維陣列中PHP

if (is_array$shoppingCartContents)) { 
    foreach($shoppingCartContents as $k=>$v) { 
     if($v[1] === 999999) { 
     unset($shoppingCartContents[$k]); 
     } 
    } 
} 


$shoppingCartContents = Array 
(
[0] => Array 
    (
     [productId] => 27 
     [productTitle] => Saffron, Dill & Mustard Mayonnaise 
     [price] => 6.50 
     [quantity] => 3 
    ) 

[1] => Array 
    (
     [productId] => 28 
     [productTitle] => Wasabi Mayonnaise 
     [price] => 6.50 
     [quantity] => 3 
    ) 

[2] => Array 
    (
     [productId] => 29 
     [productTitle] => Chilli Mayo 
     [price] => 6.50 
     [quantity] => 2 
    ) 

[3] => Array 
    (
     [productId] => 999999 
     [productTitle] => Postage 
     [price] => 8.50 
     [quantity] => 1 
    ) 
) 
+0

有一個在你的代碼可能錯字:'is_array $ shoppingCartContents)' – Jim

回答

3

只需使用array_pop()

$last_array_element = array_pop($shoppingCartContents); 
// $shoppingCartContents now has last item removed 

因此,在你的代碼:

if (is_array($shoppingCartContents)) { 
    array_pop($shoppingCartContents); // you don't care about last items, so no need to keep it's value in memory 
} 
+0

完美工作,謝謝麥克的及時回覆。 – Twobears

0

爲你使用字符串鍵,而不是數字,您的代碼會失敗,因此比較

if($v[1] === 999999)

永遠不會匹配,應該檢查$v['productId']

對於你的使用情況,而不是通過數組循環,你可以彈出的最後一項關:

array_pop($shoppingCartContents); 

array_pop刪除數組中的最後一項。它返回最後一項,但由於您不想保留最後一項,我們不保存返回值。

另外,如果你仍然想使用未設置,你可以get the last key,然後取消設置使用。

最後,因爲它看起來像你已經有了一個真正的名單(即連續,數字索引),你可以逃脫類似unset($shoppingCartContents[count($shoppingCartContents)-1]);

所有的說法,array_pop是要走的路。

相關問題