You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对比两个扁平数组,提取新增元素与重复超额元素?

解决方案

方法一:基于词频统计实现

先分别统计两个数组中每个单词的出现次数,再逐个对比处理:

  1. 用array_count_values()生成两个数组的词频统计结果
  2. 遍历待检查数组的词频,处理两种情况:
    • 单词不在正确数组的词频里:把该单词的所有出现都加入结果
    • 单词在正确数组的词频里,但出现次数更多:把超额的部分加入结果

代码示例:

$correctArray = ["The", "year", "stations", "are", "summer", "winter", "spring", "and", "fall"];
$textArray = ["The", "year", "stations", "are", "four", "summer", "winter", "and", "spring", "and", "summer"];

// 统计词频
$correctFreq = array_count_values($correctArray);
$textFreq = array_count_values($textArray);

$finalArray = [];

foreach ($textFreq as $word => $count) {
    if (!isset($correctFreq[$word])) {
        // 单词不在正确数组中,全部加入结果
        for ($i = 0; $i < $count; $i++) {
            $finalArray[] = $word;
        }
    } else {
        // 计算超额次数,添加超额部分
        $excess = $count - $correctFreq[$word];
        if ($excess > 0) {
            for ($i = 0; $i < $excess; $i++) {
                $finalArray[] = $word;
            }
        }
    }
}

print_r($finalArray);
// 输出:Array ( [0] => four [1] => and [2] => summer )

方法二:按你思路的移除匹配元素实现

复制一份正确数组的临时副本,遍历待检查数组的每个元素:

  • 如果元素在临时副本中,找到索引并移除(相当于消耗一次匹配机会)
  • 如果不在临时副本中,直接加入结果数组

代码示例:

$correctArray = ["The", "year", "stations", "are", "summer", "winter", "spring", "and", "fall"];
$textArray = ["The", "year", "stations", "are", "four", "summer", "winter", "and", "spring", "and", "summer"];

// 复制临时数组,避免修改原正确数组
$tempCorrect = $correctArray;
$finalArray = [];

foreach ($textArray as $word) {
    $index = array_search($word, $tempCorrect);
    if ($index !== false) {
        // 找到匹配元素,从临时数组移除
        array_splice($tempCorrect, $index, 1);
    } else {
        // 无匹配,加入结果数组
        $finalArray[] = $word;
    }
}

print_r($finalArray);
// 输出:Array ( [0] => four [1] => and [2] => summer )

两种方法都能得到你需要的结果,方法一更适合处理大规模数据(效率更高),方法二更贴合你最初的思路,逻辑直观。

内容的提问来源于stack exchange,提问作者Jefferson Farid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:35:18