如何使用for循环比较两个数组,并保持第一个数组的唯一性



如何使用php(例如(比较两个数组值并从第一个数组中删除重复值

$a = ['a','b','c','d','e','f'];
$b = ['a','e'];
$result_array = ['b','c','d','f'];

我试过这个:

$a = ['a','b','c','d','e','f'];
$b = ['a','e'];
foreach($a as $key_a=>$val_a){
$val = '';
foreach($b as $key_b=>$val_b){
if($val_a != $val_b){
$val = $val_a;    
}else{$val = $val_b;}
}
echo $val."<br>";
}

这可能是重复的,但我很无聊。只需计算差异:

$a = array_diff($a, $b);

或者循环主数组,检查另一个数组中的每个值,如果发现主数组中未设置:

foreach($a as $k => $v) {
if(in_array($v, $b)) {
unset($a[$k]);
}
}

或者循环另一个数组,搜索主数组中的每个值,并使用找到的键取消设置:

foreach($b as $v) {
if(($k = array_search($v, $a)) !== false) {
unset($a[$k]);
}
}

看看这篇SO文章看看Edit3
Edit2我们使用此代码来比较两个ArrayList,并从其中删除重复项,因为我们只想要拼写错误的单词
代码捕获的示例是ArrayList

for(int P = 0; P < capture.size();P++){
String gotIT = capture.get(P);     
String[] EMPTY_STRING_ARRAY = new String[0];
List<String> list = new ArrayList<>();
Collections.addAll(list, strArray);
list.removeAll(Arrays.asList(gotIT));
strArray = list.toArray(EMPTY_STRING_ARRAY); 
// Code above removes the correct spelled words from ArrayList capture
// Leaving the misspelled words in strArray then below they are added 
// to the cboMisspelledWord which then holds all the misspelled words
}

您可以将$b制作为字典,当两个数组具有多个元素时,它将具有更好的性能。检查演示

$a = ['a','b','c','d','e','f'];
$b = ['a','e'];
$dic = array_flip($b);
$result = array_filter($a, function($v)use($dic){return !isset($dic[$v]);});
print_r($result);

最新更新