比较相同的数组值
在 PHP 中比较同一数组中的元素的最佳方法是什么,以便如果数组 A 中有两个元素具有相同的值,我可以传递一个函数作为参数来执行某些操作?
What is the best way to compare elments in the same array in PHP, so that if there are two elemets with the same values in array A, I can pass a function as argument to do somthing ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
array_count_values
和in_array
的功能如下:You can use
array_count_values
andin_array
functions as:如果您想查找数组中重复的所有值,您可以执行以下操作:
上面的输出将是:
如果您的数组有自定义键(如注释数组中所示),则输出将是:
If you want to find all values that are duplicated in an array you could do something like this:
The output from the above would be:
If your array had custom keys (as in the commented array) the output would be:
我假设您不想合并到数组然后删除重复项。
I assume you wan't to merge to array and then remove duplicates.
使用 array_udiff 或类似的(如果您希望能够修改值,请在回调中使用引用参数):
Use array_udiff or similar (with reference arguments in the callback, if you want to be able to modify the values):