php 如果它不存在,则添加到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6083567/
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
add to array if it isn't there already
提问by user657821
How do I add elements to an array only if they aren't in there already? I have the following:
仅当元素不在数组中时,如何将元素添加到数组中?我有以下几点:
$a=array();
// organize the array
foreach($array as $k=>$v){
foreach($v as $key=>$value){
if($key=='key'){
$a[]=$value;
}
}
}
print_r($a);
// Output
// 输出
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 1
[4] => 2
[5] => 3
[6] => 4
[7] => 5
[8] => 6
)
Instead, I want $a to consist of the unique values. (I know I can use array_unique to get the desired results but I just want to know)
相反,我希望 $a 包含唯一值。(我知道我可以使用 array_unique 来获得想要的结果,但我只是想知道)
回答by Marius Schulz
You should use the PHP function in_array
(see http://php.net/manual/en/function.in-array.php).
您应该使用 PHP 函数in_array
(请参阅http://php.net/manual/en/function.in-array.php)。
if (!in_array($value, $array))
{
$array[] = $value;
}
This is what the documentation says about in_array
:
这是文档所说的内容in_array
:
Returns TRUEif needle is found in the array, FALSEotherwise.
如果在数组中找到针,则返回TRUE,否则返回FALSE。
回答by onteria_
回答by Gumbo
Since you seem to only have scalar valuesan PHP's array is rather a hash map, you could use the value as key to avoid duplicates and associate the $k
keys to them to be able to get the original values:
由于您似乎只有标量值,因此 PHP 的数组更像是一个哈希映射,您可以使用该值作为键来避免重复并将$k
键与它们相关联以获取原始值:
$keys = array();
foreach ($array as $k => $v){
if (isset($v['key'])) {
$keys[$value] = $k;
}
}
Then you just need to iterate it to get the original values:
然后你只需要迭代它以获得原始值:
$unique = array();
foreach ($keys as $key) {
$unique[] = $array[$key]['key'];
}
This is probably not the most obvious and most comprehensive approach but it is very efficient as it is in O(n).
这可能不是最明显和最全面的方法,但它非常有效,因为它在 O( n) 中。
Using in_array
instead like others suggested is probably more intuitive. But you would end up with an algorithm in O(n2) (in_array
is in O(n)) that is not applicable. Even pushing all values in the array and using array_unique
on it would be better than in_array
(array_unique
sorts the values in O(n·log n) and then removes successive duplicates).
in_array
像其他人建议的那样使用可能更直观。但是你最终会得到一个不适用的O( n 2) (in_array
在 O( n) 中)的算法。即使推送数组中的所有值并array_unique
在其上使用也比in_array
(array_unique
对 O( n·log n) 中的值进行排序,然后删除连续的重复项)更好。
回答by Sourav
if (!in_array(...))
array_push(..)
回答by peschanko
Easy to write, but not the most effective one:
易于编写,但不是最有效的:
$array = array_unique(array_merge($array, $array_to_append));
This one is probably faster:
这个可能更快:
$array = array_merge($array, array_diff($array_to_append, $array));
回答by CristiC
if (!in_array($value, $a))
$a[]=$value;
回答by marcosh
If you don't care about the ordering of the keys, you could do the following:
如果您不关心键的顺序,您可以执行以下操作:
$array = YOUR_ARRAY
$unique = array();
foreach ($array as $a) {
$unique[$a] = $a;
}
回答by akentner
Try adding as key instead of value:
尝试添加为键而不是值:
Adding an entry
添加条目
function addEntry($entry) {
$this->entries[$entry] = true;
}
Getting all entries
获取所有条目
function getEntries() {
return array_keys($this->enties);
}
回答by fyrye
Since there are a ton of ways to accomplish the desired results and so many people provided !in_array()
as an answer, and the OP already mentions the use of array_unique
, I would like to provide a couple alternatives.
由于有很多方法可以实现预期的结果,并且提供!in_array()
了很多人作为答案,并且 OP 已经提到了使用array_unique
,我想提供一些替代方案。
Using array_diff
(php >= 4.0.1 || 5) you can filter out only the new array values that don't exist. Alternatively you can also compare the keys and values with array_diff_assoc
. http://php.net/manual/en/function.array-diff.php
使用array_diff
(php >= 4.0.1 || 5) 您可以仅过滤掉不存在的新数组值。或者,您也可以将键和值与array_diff_assoc
. http://php.net/manual/en/function.array-diff.php
$currentValues = array(1, 2);
$newValues = array(1, 3, 1, 4, 2);
var_dump(array_diff($newValues, $currentValues));
Result:
结果:
Array
(
[1] => 3
[3] => 4
)
Another method is using array_flip
to assign the values as keys and compare them using isset
, which will perform much faster than in_array
with large datasets. Again this filters out just the new values that do not already exist in the current values.
另一种方法是使用array_flip
将值分配为键并使用 比较它们isset
,这将比in_array
大型数据集执行得快得多。这再次过滤掉当前值中尚不存在的新值。
$currentValues = [1, 2];
$newValues = [1, 3, 1, 4, 2];
$a = array();
$checkValues = array_flip($currentValues);
foreach ($newValues as $v) {
if (!isset($checkValues[$v])) {
$a[] = $v;
}
}
Result:
结果:
Array
(
[0] => 3
[1] => 4
)
With either method you can then use array_merge
to append the unique new values to your current values.
无论使用哪种方法,您都可以array_merge
将唯一的新值附加到当前值。
Result:
结果:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
回答by Márton Tamás
If you're okay with using shorthandsin your code (instead of writing explicit if
blocks, like some coding standardsrecommend), you can further simplify Marius Schulz's answerwith this one-liner:
如果您可以在代码中使用速记(而不是if
像某些编码标准推荐的那样编写显式块),您可以使用以下单行代码进一步简化Marius Schulz 的答案:
in_array ($value, $array) || $array [] = $value;