PHP 中内置对集合的支持吗?
我正在寻找一种在 php 中创建数组的简单方法,该方法不允许重复条目,但允许轻松组合其他集或数组。
我最感兴趣的是该语言中是否存在这样的功能,因为编写我自己的功能并不困难。我只是不想,如果不需要的话。
I'm looking for a simple way to create an array in php that will not allow duplicate entries, but allows for easy combining of other sets or arrays.
I'm mostly interested in whether such a feature exists in the language because writing my own wouldn't be difficult. I just don't want to if I don't need to.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
只是一个想法,如果您使用数组键而不是值,您将确保没有重复项,而且这还可以轻松合并两个“集”。
Just an idea, if you use the array keys instead of values, you'll be sure there are no duplicates, also this allows for easy merging of two "sets".
答案是否定的,PHP内部没有原生的set解决方案。有一个
Set
数据结构 ,但这不是基线 PHP。在任何语言中使用映射(即关联数组)实现集合都有一个约定。对于 PHP,您应该使用
true
作为底部值。The answer is no, there is not a native set solution inside PHP. There is a
Set
data structure, but that is not baseline PHP.There is a convention for implementing sets using maps (i.e. associative arrays) in any language. And for PHP you should use
true
as the bottom value.您可以使用 array_combine 来删除重复项
You can use array_combine for removing duplicates
Set 类。
https://www.php.net/manual/en/class。 ds-set.php
不知道什么时候出。
The Set class.
https://www.php.net/manual/en/class.ds-set.php
Don't know when will it come out.
我也遇到了这个问题,所以写了一个类: https://github.com/jakewhiteley/php -set-object
正如所建议的,它确实扩展了 ArrayObject 并允许本机感觉的值插入/迭代/删除,但不在任何地方使用 array_unique() 。
实现基于 EMCA 6 JavaScript 中的 MDN JS 文档集。
I also had this problem and so have written a Class: https://github.com/jakewhiteley/php-set-object
As suggested, it does extend and ArrayObject and allow native-feeling insertion/iteration/removal of values, but without using
array_unique()
anywhere.Implementation is based on the MDN JS Docs for Sets in EMCA 6 JavaScript.
在 Laravel 中,
Collection
类中有一个方法unique
可能会有所帮助。来自 Laravel 文档:In Laravel there is a method
unique
inCollection
class that may be helpful. From Laravel documentation:我需要在项目中使用 Set 来保存唯一的对象。为此,您可以使用
spl_object_id
或spl_object_hash
。注意:使用
spl_object_id
时,不要将数组与array_merge
或[...$array1, ...$array2]
合并,因为它们会重新排序整数键。使用$array1 + $array2
保留现有键。这种向数组添加对象的方式可以包装在一个类中,以确保仅添加对象并且使用
spl_object_id
添加所有对象。I needed a Set in a project to save unique objects. To do that you can use
spl_object_id
orspl_object_hash
.Note: When using
spl_object_id
dont't merge arrays witharray_merge
or[...$array1, ...$array2]
because those reorder integer keys. Use$array1 + $array2
to keep existing keys.This way of adding objects to the arrays could be wrapped in a class to make sure only objects are added and all objects are added using
spl_object_id
.