PHP数组问题
我需要使用一些随机值来填充数组,但如果在数组中重复,我的应用程序无法正常工作.所以我需要编写脚本代码,它将找到重复项并用其他一些值替换它们.
好的,例如我有一个数组:
<?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;
}
?>
因此,结果应为具有替换重复值的相同数组.
谢谢你的帮助.
解决方法:
你可以跟踪你到目前为止看到的单词并随时替换.
// 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;
}
}