可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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]