如何在对数字键重新编号时从数组中删除值
我有一个可能包含数字或关联键或两者的数组:
$x = array('a', 'b', 'c', 'foo' => 'bar', 'd', 'e');
print_r($x);
/*(
[0] => a
[1] => b
[2] => c
[foo] => bar
[3] => d
[4] => e
)*/
我希望能够从数组中删除一个项目,对非关联键重新编号以保持它们的顺序:
$x = remove($x, "c");
print_r($x);
/* desired output:
(
[0] => a
[1] => b
[foo] => bar
[2] => d
[3] => e
)*/
找到要删除的正确元素不是问题,而是有问题的钥匙。 unset
不会对键重新编号,并且 array_splice
适用于偏移量,而不是键(即:从第一个示例中获取 $x ,array_splice($x, 3, 1)
将删除“bar”元素而不是“d”元素)。
I have an array which may contain numeric or associative keys, or both:
$x = array('a', 'b', 'c', 'foo' => 'bar', 'd', 'e');
print_r($x);
/*(
[0] => a
[1] => b
[2] => c
[foo] => bar
[3] => d
[4] => e
)*/
I want to be able to remove an item from the array, renumbering the non-associative keys to keep them sequential:
$x = remove($x, "c");
print_r($x);
/* desired output:
(
[0] => a
[1] => b
[foo] => bar
[2] => d
[3] => e
)*/
Finding the right element to remove is no issue, it's the keys that are the problem. unset
doesn't renumber the keys, and array_splice
works on an offset, rather than a key (ie: take $x from the first example, array_splice($x, 3, 1)
would remove the "bar" element rather than the "d" element).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这应该在保留字符串键的同时重新索引数组:
This should re-index the array while preserving string keys:
您可以使用下一个优雅的解决方案进行修复:
例如:
You can fixet with next ELEGANT solution:
For example:
我想出了这个 - 尽管我不确定它是否是最好的:
为了简洁起见,我省略了一些内容。例如,在使用上述代码之前,您需要检查数组是否是关联的,以及要删除的键是否是字符串。
I've come up with this - though I'm not sure if it's the best:
There's a few things I've left out, just for the sake of brevity. For example, you'd check if the array is associative, and also if the key you're removing is a string or not before using the above code.
尝试 array_diff() 它可能无法正确排序新数组
如果不是,以下应该可以工作,
您将需要在删除函数中迭代它。
直流
Try array_diff() it may not order the new array correctly though
if not the following should work
You will need to iterate over it in the remove function.
DC
我认为这个问题没有一个优雅的解决方案,您可能需要循环到数组并自己重新排序键。
I don't think there is an elegant solution to this problem, you probably need to loop to the array and reorder the keys by yourself.