【问题标题】:How to compare two arrays using a for loop and keep the unique from first array?如何使用 for 循环比较两个数组并保持第一个数组的唯一性?
【发布时间】:2019-11-20 21:15:09
【问题描述】:

例如如何比较两个数组值并使用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>";
}

【问题讨论】:

    标签: php arrays for-loop


    【解决方案1】:

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

    $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]);
        }
    }
    

    【讨论】:

    • “这可能是重复的,但我很无聊” 我知道那是什么感觉 :-)。另外,找到骗子通常比发布答案需要更长的时间......
    【解决方案2】:

    看看这个 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
    }
    

    【讨论】:

      【解决方案3】:

      你可以把$b做成一个字典,这样当两个数组有很多元素的时候性能会更好。检查Demo

      $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);
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-19
        • 1970-01-01
        • 2015-07-19
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        相关资源
        最近更新 更多