2012-01-11 36 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); 
} 
相關問題