在数组中查找和替换重复项

4
我可以帮助您进行翻译。以下是需要翻译的内容:

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

<?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;
}
?>

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

1
在需要编写自己的方法之前,您可能需要先查看array_unique()array_replace(),它们可能正是您所需的。 - newfurniturey
我检查了一下,它不符合我的需求。感谢你的帮助。 - xZero
如果您表达出要使用的替换字符串和您期望的确切结果,这个问题会更清晰。一个 [mcve] @xZero - mickmackusa
4个回答

3
你可以随时追踪你已经看过的单词,并在需要时进行替换。
// 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() 函数(参考文档)来计算出现次数。

// 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;
    }
}

2

以下是如何生成唯一值并替换数组中重复值的示例:

function get_unique_val($val, $arr) {
    if ( in_array($val, $arr) ) {
        $d = 2; // initial prefix 
        preg_match("~_([\d])$~", $val, $matches); // check if value has prefix
        $d = $matches ? (int)$matches[1]+1 : $d;  // increment prefix if exists

        preg_match("~(.*)_[\d]$~", $val, $matches);

        $newval = (in_array($val, $arr)) ? get_unique_val($matches ? $matches[1].'_'.$d : $val.'_'.$d, $arr) : $val;
        return $newval;
    } else {
        return $val;
    }
}

function unique_arr($arr) {
    $_arr = array();
    foreach ( $arr as $k => $v ) {
        $arr[$k] = get_unique_val($v, $_arr);
        $_arr[$k] = $arr[$k];
    }
    unset($_arr);

    return $arr;
}




$ini_arr = array('dd', 'ss', 'ff', 'nn', 'dd', 'ff', 'vv', 'dd');

$res_arr = unique_arr($ini_arr); //array('dd', 'ss', 'ff', 'nn', 'dd_2', 'ff_2', 'vv', 'dd_3');

Full example you can see here webbystep.ru


1

谢谢你尝试帮助我。但它只是删除重复项。我想要替换重复项而不是删除它。 - xZero
这可能会减小数组的大小 - OP 不想要这个。 - mickmackusa

-1
$uniques = array();
foreach ($charset as $value) 
   $uniques[$value] = true;
$charset = array_flip($uniques);

1
谢谢。但是如何使用它?例如,在哪里指定将用哪些值替换重复项? - xZero
这可能会减小数组的大小 - OP 不想要这个。 - mickmackusa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接