我想我可能没有正确理解 array_splice 应该如何工作。我的理解是,第一个参数是您的初始数组,第二个参数是开始的元素,第三个参数是长度或要删除/替换的元素数。
所以,我有这个数组(print_r 输出):
Array (
[0] => Array ( [TypeFlag] => S [qty] => 1 [denom] => 25 [certMessage] => [totalPrice] => 25 )
[1] => Array ( [TypeFlag] => C [qty] => 2 [denom] => 25 [certMessage] => [totalPrice] => 50 )
[2] => Array ( [TypeFlag] => V [qty] => 2 [denom] => 25 [certMessage] => test [totalPrice] => 50 ) )
我想完全删除第二个元素(索引为 1 的数组;TypeFlag = C 等)我不想用任何东西替换它;只是返回包含剩余两个元素的数组。我试过这个(其中 cart 是数组名称):
$cart = array_splice($cart, 1,1);
但我在执行 print_r 时最终得到的是:
Array ( [0] => Array ( [TypeFlag] => C [qty] => 2 [denom] => 25 [certMessage] => [totalPrice] => 50 ) )
所以它似乎是删除 0 和 2,并留下 1 作为余数。我做错了什么?
最佳答案
array_splice
返回一个由提取的元素组成的数组。
你正在做:
$cart = array_splice($cart, 1,1);
因此您正在提取第二个元素(索引 1)并将结果分配回 $cart
,覆盖您的原始数组。
要完全删除第二个元素,请不要将 array_splice
的返回值分配回 $cart
。所以就这样做:
array_splice($cart, 1,1);
之所以可行,是因为数组是通过引用传递给函数的。
此外,如果您想从数组中删除单个元素,使用 unset
会更高效、更简洁:
unset($cart[1]);
关于php - 如何在 php 中使用 array_splice 删除单个数组成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3805134/