php - 查找并替换数组中的重复项

标签 php arrays replace find duplicates

我需要制作应用程序,将用一些随机值填充数组,但如果数组中有重复项,我的应用程序将无法正常工作。所以我需要编写脚本代码来查找重复项并将它们替换为其他一些值。 好的,例如我有一个数组:

<?PHP
$charset=array(123,78111,0000,123,900,134,00000,900);

function arrayDupFindAndReplace($array){

// if in array are duplicated values then -> Replace duplicates with some other numbers which ones I'm able to specify.
return $ArrayWithReplacedValues;
}
?>

因此结果应该是替换了重复值的同一个数组。

最佳答案

您可以只记录到目前为止看到的单词并随时替换。

// words we've seen so far
$words_so_far = array();
// for each word, check if we've encountered it so far
//    - if not, add it to our list
//    - if yes, replace it
foreach($charset as $k => $word){
    if(in_array($word, $words_so_far)){
        $charset[$k] = $your_replacement_here;
    }
    else {
        $words_so_far[] = $word;
    }
}

对于稍微优化的解决方案(对于没有那么多重复项的情况),使用 array_count_values() (reference here)计算它出现的次数。

// counts the number of words
$word_count = array_count_values($charset);
// words we've seen so far
$words_so_far = array();
// for each word, check if we've encountered it so far
//    - if not, add it to our list
//    - if yes, replace it
foreach($charset as $k => $word){
    if($word_count[$word] > 1 && in_array($word, $words_so_far)){
        $charset[$k] = $your_replacement_here;
    }
    elseif($word_count[$word] > 1){
        $words_so_far[] = $word;
    }
}

关于php - 查找并替换数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13215668/

相关文章:

c++ - 在 C++ 中旋转数组的最后 n 个元素

c++ - std::length_error 尝试从类数组输出字符串时

arrays - 如何将 ArrayFormula 与数组一起使用(聚合后)?

javascript正则表达式将所有重复的选项卡新行替换为单个新行

java - Java中的RegEx替换字符串

php - 使用 PHP 获取 SQL-Server 中的行数

javascript - 在 JsonP 中得到不正确的响应

php - 用于显示之前日期的简单脚本

php - 如何在 Mac OS 中安装 PHP 的 MSSQL 驱动程序

json - 替换\"with "的实例