gpt4 book ai didi

PHP:如何识别和更改数组中的重复值?

转载 作者:搜寻专家 更新时间:2023-10-31 21:42:55 24 4
gpt4 key购买 nike

好的,在 php 数组中有很多重复检测和删除的例子,使用 array_unique() 等,但是如果你想找到重复项,修改它们,再次循环检查直到所有重复项现在都是唯一的怎么办?

我认为这有点像使用 array_filter()...所以作为一个更具体的例子,下面是像这样的 sql 语句会产生的结果:

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 来删除句点之前的字符,这样它们是唯一的[或者如果需要的话在末尾添加数字]

所以结果是:

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 和 another.duplicate)...我查看了几乎所有 PHP 数组函数,试图想出一个策略...想法?

最佳答案

对于您问题中的数组以及如果重复则在末尾添加数字,您只需要遍历数组一次并临时构建一个辅助数组来存储是否已经找到一个值(以及频率) :

$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);

Demo

关于PHP:如何识别和更改数组中的重复值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8205031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com