2

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

例子

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

谢谢

4

2 回答 2

2

试试这个,以获得比其他解决方案潜在的速度提升。然而,将在大型数据集上使用更多内存。

<?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);
于 2013-07-29T17:51:43.373 回答
1

这应该做你想要的。循环遍历数组,看看值是否已经存在。如果是这样,请将其添加到结果中。

$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

于 2013-07-29T17:27:55.377 回答