在一个数组中查找重复值,该数组将创建一个新数组,其中键作为重复键,值作为重复项


Find duplicate values in an array which creates a new array with key as duplicate keys and values as the dupes

我正在尝试在数组中查找所有重复项,并创建一个新数组,该数组的键作为重复值键,值作为其重复的键

示例

[1] => 10
[2] => 11
[3] => 12
[4] => 12
[5] => 12
[6] => 13
[7] => 13

在我申请重复检查后,我只需要

[4] => [3] // value of key 4 is dupe of key 3
[5] => [3] // value of key 5 is dupe of key 3
[7] => [6] // value of key 7 is dupe of key 6

这得到了我所有的重复密钥,但我需要具有值的重复密钥作为重复的密钥

$arr_duplicates = array_keys(array_unique( array_diff_assoc( $array, array_unique( $array ) ) ));

感谢

与其他解决方案相比,尝试此解决方案可以提高速度。然而,在大型数据集上会使用更多的内存。

<?php
$orig = array(
    1   => 10,
    2   => 11,
    3   => 12,
    4   => 12,
    5   => 12,
    6   => 13,
    7   => 13
);
$seen  = array();
$dupes = array();
foreach ($orig as $k => $v) {
    if (isset($seen[$v])) {
        $dupes[$k] = $seen[$v];
    } else {
        $seen[$v] = $k;
    }
}
unset($seen);
var_dump($dupes);

这应该是您想要的。在数组上循环,查看值是否已经在其中。如果是,请将其添加到结果中。

$arr_duplicates = array();
foreach($array as $k=>$v){
    // array_search returns the 1st location of the element
    $first_index = array_search($v, $array);
    // if our current index is past the "original" index, then it's a dupe
    if($k != $first_index){
        $arr_duplicates[$k] = $first_index;
    }
}

演示:http://ideone.com/Kj0dUV