查找和替换阵副本 [英] Find and replace duplicates in Array
问题描述
PHP数组问题
我需要与应用将填补阵列用一些随机值,但如果阵列是重复我的应用程序无法正常工作。所以,我需要编写脚本code,将查找重复,并与一些其它值替换它们。
好了,比如我有一个数组:
PHP Array Question I need to make app with will fill array with some random values, but if in array are duplicates my app not working correctly. So i need to write script code which will find duplicates and replace them with some other values. Okay so for example i have an array:
<?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 im able to specify.
return $ArrayWithReplacedValues;
}
?>
这样的结果应是同一阵列替换为重复值。
So result shall be same array with replaced duplicated values.
感谢您的帮助。
推荐答案
您可以只跟踪你已经迄今所看到和替换,当您去的话。
You can just keep track of the words that you've seen so far and replace as you go.
// 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()的(参考这里)来计算的次数就出现了。
For a somewhat-optimized solution (for cases where there are not that many duplicates), use array_count_values() (reference here) to count the number of times it shows up.
// 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;
}
}
这篇关于查找和替换阵副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!