好的,在 php 数组中有很多重复检测和删除的例子,使用 array_unique() 等但是如果你想找到 dups,修改它们,在循环中再次检查,直到所有 dup 现在都是唯一的?
OK, there are a lot of examples of duplicate detection and removal in php arrays, using array_unique() etc but what if you want to find dups, modify them, check again in a loop until all dups are now unique?
我认为这有点像使用 array_filter()... 所以作为一个更具体的例子,下面是一个类似这样的 sql 语句的结果:
I think it's something like using array_filter()... so as a more specific example, here's what would come out of a sql statement something like this:
SELECT id, list.comboname
FROM list
INNER JOIN (
SELECT comboname
FROM list
GROUP BY comboname
HAVING count(id) > 1
) dup ON list.comboname = dup.comboname
到表中重复的数组:
Array (
[0] => 49
[1] => big.dup
[2] => 233
[3] => another.duplicate
[4] => 653
[5] => big.dup
[6] => 387
[7] => big.dup
[8] => 729
[9] => another.duplicate
[10] => 1022
[11] => big.dup
)
现在我想要的是一些 PHP 删除字符直到句号,所以它们是唯一的 [或者如果需要在末尾添加数字]
Now what I want is some PHP to delete characters until the period so they are unique [or add numbers if needed to the end]
所以结果是:
Array (
[0] => 49
[1] => big.dup
[2] => 233
[3] => another.duplicate
[4] => 653
[5] => big.du
[6] => 387
[7] => big.d
[8] => 729
[9] => another.duplicat
[10] => 1022
[11] => big.dup1
)
在保留原始值(即 big.dup 和另一个
While retaining the original value (i.e. big.dup and another.duplicate)... I've looked through just about every PHP array function trying to imagine a strategy ... ideas?
对于你问题中的数组,如果重复的话,在末尾添加数字,你只需要循环一次数组并临时构建一个辅助数组存储是否已经找到值(以及多久):
For the array in your question and for adding numbers at the end if a duplicate, you only need to loop over the array once and temporary build up a helper array that stores if a value has been already found (and how often):
$found = array();
foreach($array as &$value)
{
if (is_int($value)) continue; # skip integer values
if (isset($found[$value]))
{
$value = sprintf('%s-%d', $value, ++$found[$value]);
}
else
{
$found[$value] = 0;
}
}
unset($value);
演示
这篇关于PHP:如何识别和更改数组中的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!