好的,在 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)