如何确定二维数组中是否存在重复项

时间:2012-01-11 13:23:57

标签: php arrays multidimensional-array

我有一个这样的数组:

Array(
   ["dest0"] => Array(
                  ["id"] => 1,
                  ["name"] => name1   
                 ),    
   ["dest1"] => Array(
                  ["id"] => 2,
                  ["name"] => name2  
                 ),   
  ["dest2"] => Array(
                  ["id"] => 3,
                  ["name"] => name3  
                 ),   
  ["dest3"] => Array(
                  ["id"] => 1,
                  ["name"] => name1   
                 )
);    

并且想要检查其中的重复值(就像这里dest0和dest3是重复的一样),我不希望它像here一样删除它们,juste检查是否有任何。

感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码找出重复内容(如果有):

// assuming $arr is your original array
$narr = array();
foreach($arr as $key => $value) {
   $narr[json_encode($value)] = $key;
}
if (count($arr) > count($narr))
   echo "Found duplicate\n";
else
   echo "Found no duplicate\n";

答案 1 :(得分:1)

完全基于检查重复的id而不是id和name,但很容易修改:

$duplicates = array();
array_walk($data, function($testValue, $testKey) use($data, &$duplicates){
                        foreach($data as $key => $value) {
                            if (($value['id'] === $testValue['id']) && ($key !== $testKey))
                                return $duplicates[$testKey] = $testValue;
                        }
                    } );

if (count($duplicates) > 0) {
    echo 'You have the following duplicates:',PHP_EOL;
    var_dump($duplicates);
}