PHP 提供了一个闭包来确定数组中项目的唯一性
简单的问题:有没有一种方法可以在 PHP 中为 array_unique 函数的某个等效函数提供一个闭包,以便您可以在比较数组中的两个项目时指定要使用的自己的比较闭包?我有一个类实例数组(可能包含重复项),并且想要告诉 PHP 使用特定逻辑来确定唯一性。
PHP 使用 usort() 方法提供了排序功能 - 只是想知道它是否也可用于唯一性检查。谢谢!
Quick question: is there a way to provide a closure in PHP to some equivalent function to the array_unique function so that you can specify your own comparison closure to be used when comparing two items in the array? I have an array of class instances (which may contain duplicates) and want to tell PHP to use particular logic to determine uniqueness.
PHP provides this with sorting using the usort() method - just wondering if it is also available for uniqueness checks. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
array_filter 可以对数组中的每个元素应用回调,并返回 true/false 是否将该值保留在返回数组中。 这是一条注释,使用 array_filter 删除重复项一个数组。
there is array_filter that you can apply a callback to each element in an array and return true/false of whether to keep that value in the returning array. Here is a comment using array_filter to remove duplicates in an array.
我找不到你正在寻找的确切内容,但我想编写你自己的函数也许不会太难......
I couldn't find exactly what you are looking for but i thought maybe it wouldn't be too tough to write your own function...
array_unique()手册页 code> 不提供任何指向回调版本的链接,并且左侧链接列表中没有名为
array_uunique()
的函数(如果是这样的话,应该调用该函数)它遵循其他数组排序函数的命名约定 - 但 PHP 在函数命名约定方面并不是很可靠)。您可以使用双
foreach
循环自行添加此功能:The manual page for
array_unique()
doesn't provide any links to a callback version, and there isn't a function in the list of links on the left calledarray_uunique()
(which is what such a function should be called if it follows the naming convention of the other array sorting functions - but then PHP isn't very reliable when it comes to function naming conventions).You could add this functionality yourself using a double
foreach
loop: