PHP: How to identify AND CHANGE duplicate values in an array?(PHP:如何识别和更改数组中的重复值?)
问题描述
好的,在 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:如何识别和更改数组中的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP:如何识别和更改数组中的重复值?
基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01