数组合并&数组唯一
PHP 中是否有一个数组函数可以以某种方式执行 array_merge,比较值,忽略键?我认为 array_unique(array_merge($a, $b)) 有效,但是我相信一定有更好的方法来做到这一点。
例如。
$a = array(0 => 0, 1 => 1, 2 => 2);
$b = array(0 => 2, 1 => 3, 2 => 4);
结果:
$ab = array(0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4);
请注意,我不关心 $ab
中的键,但是如果它们是升序的,从 0 开始到 count,那就太好了 ($ab)-1
。
Is there an array function in PHP that somehow does array_merge, comparing the values, ignoring the keys? I think that array_unique(array_merge($a, $b))
works, however I believe there must be a nicer way to do this.
eg.
$a = array(0 => 0, 1 => 1, 2 => 2);
$b = array(0 => 2, 1 => 3, 2 => 4);
resulting in:
$ab = array(0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4);
Please note that I don't care about the keys in $ab
, however it would be nice if they were ascending, starting at 0 to count($ab)-1
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最优雅、最简单、最有效的解决方案是原始问题中提到的解决方案...
这个答案之前也在 Ben Lee 和 doublejosh 的评论中提到过,但我将其发布在这里作为实际答案,以造福其他人发现此问题并想知道最佳解决方案是什么的人,无需阅读此页面上的所有评论。
The most elegant, simple, and efficient solution is the one mentioned in the original question...
This answer was also previously mentioned in comments by Ben Lee and doublejosh, but I'm posting it here as an actual answer for the benefit of other people who find this question and want to know what the best solution is without reading all the comments on this page.
为了回答所提出的问题,对于在保留键的同时也可以使用关联数组的通用解决方案,我相信您会发现这个解决方案最令人满意:
To answer the question as asked, for a general solution that also works with associative arrays while preserving keys, I believe that you will find this solution most satisfactory:
array_merge 将忽略数字键,因此在您的示例中
array_merge($a, $b)
将为您提供$ab
,无需调用array_unique()
。如果您有字符串键(即关联数组),请首先使用 array_values() :
array_merge will ignore numeric keys, so in your example
array_merge($a, $b)
would give you$ab
, there is no need to callarray_unique()
.if you have string keys (i.e. an associative array) use
array_values()
first: