2012-01-11 76 views
1

我有一个这样的数组:如何确定是否有一个二维数组重复

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一样将它们移除,只要有任何检查即可。

谢谢。

+0

你意味着你需要更高效的方式? – Orentet 2012-01-11 13:26:56

+0

只有两个维度还是可以有任意维度? – Gumbo 2012-01-11 13:27:34

+0

@Gumbo只是在这个例子中的两个维度。 – 2012-01-11 13:31:42

回答

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"; 
+0

非常感谢! – 2012-01-11 13:59:32

1

在检查重复的ID,而不是两个编号和名称纯粹是基于,但很容易修改:

$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); 
} 
相关问题