Built in support for sets in PHP?

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

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.

回答1:

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".

$set1 = array ('a' => 1, 'b' => 1, ); $set2 = array ('b' => 1, 'c' => 1, ); $union = $set1 + $set2; 


回答2:

Found a solution: array_unique

Just add the items to an array, then call array_unique to remove duplicates, which ultimately achieves the same effect. Only downside is you have to remember to call it. Would be better if there were an actual class to manage that, but this is fine for my purposes.



回答3:

You can use array_combine for removing duplicates

$cars = array("Volvo", "BMW", "Toyota"); array_push($cars,"BMW");  $map = array_combine($cars, $cars); 


回答4:

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.



回答5:

In Laravel there is a method unique in Collection class that may be helpful. From Laravel documentation:

$collection = collect([1, 1, 2, 2, 3, 4, 2]); $unique = $collection->unique(); $unique->values()->all(); // [1, 2, 3, 4] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!