内置对 PHP 集合的支持?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8127384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:00:39  来源:igfitidea点击:

Built in support for sets in PHP?

phpset

提问by devios1

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.

我正在寻找一种在 php 中创建数组的简单方法,该方法不允许重复条目,但允许轻松组合其他集合或数组。

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.

我最感兴趣的是语言中是否存在这样的功能,因为编写我自己的功能并不困难。如果我不需要,我只是不想。

回答by zrvan

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;

回答by William Entriken

The answer is no, there is not a native set solution inside PHP. There is a Setdata structure, but that is not baseline PHP.

答案是否定的,PHP 内部没有本地集解决方案。有一个Set数据结构,但这不是基线 PHP。

There is a convention for implementing sets using maps (i.e. associative arrays) in any language. And for PHP you should use trueas the bottom value.

在任何语言中都有使用映射(即关联数组)实现集合的约定。对于 PHP,您应该将其true用作底部值。

<?php

$left = [1=>true, 5=>true, 7=>true];
$right = [6=>true, 7=>true, 8=>true, 9=>true];

$union = $left + $right;
$intersection = array_intersect_assoc($left, $right);

var_dump($left, $right, $union, $intersection);

回答by Preetam Purbia

You can use array_combine for removing duplicates

您可以使用 array_combine 删除重复项

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

$map = array_combine($cars, $cars);

回答by mp31415

In Laravel there is a method uniquein Collectionclass that may be helpful. From Laravel documentation:

在 Laravel 中uniqueCollection类中有一个方法可能会有所帮助。从 Laravel文档

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

回答by Jake Whiteley

I also had this problem and so have written a Class: https://github.com/jakewhiteley/php-set-object

我也有这个问题,所以写了一个类: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.

正如所建议的,它确实扩展了 ArrayObject 并允许原生感觉的值插入/迭代/删除,但不使用array_unique()任何地方。

Implementation is based on the MDN JS Docs for Sets in EMCA 6 JavaScript.

实现基于 MDN JS Docs for Sets in EMCA 6 JavaScript。