【问题标题】:How do I delete the last array item in a two dimensional array in PHP如何在PHP中删除二维数组中的最后一个数组项
【发布时间】:2012-12-24 08:04:06
【问题描述】:

我有一个二维数组,并希望在将其放入 SESSION 之前,始终删除/取消设置下面代码示例中的最后一个数组项(在本例中为 Array[3])。
我仍然是 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
    )
)

【问题讨论】:

  • 您的代码中可能存在拼写错误:is_array$shoppingCartContents)

标签: php


【解决方案1】:

只需使用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
}

【讨论】:

    【解决方案2】:

    您的代码将失败,因为您使用字符串作为键,而不是数字,所以比较

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

    永远不会匹配,应该检查$v['productId']

    对于您的用例,您可以只弹出最后一项,而不是循环遍历数组:

    array_pop($shoppingCartContents);
    

    array_pop 从数组中删除最后一项。它返回最后一项,但由于您不想保留最后一项,我们不保存返回值。

    或者,如果您仍想使用 unset,您可以get the last key,然后使用它取消设置。

    最后,看起来您有一个真实的列表(即连续的数字索引),您可以使用类似unset($shoppingCartContents[count($shoppingCartContents)-1]);

    话虽如此,array_pop 是要走的路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多