2012-03-23 43 views
1

重複我在PHP這樣的二維數組:發現在php二維數組

Array (
     [0] => Array 
      (
         [index1] => -1 
         [index2] => 77 
         [description] => 7 
        ) 
     [1] => Array 
      (
         [index1] => -1 
         [index2] => 77 
         [description] => 5 
        ) 
     [2] => Array 
      (
         [index1] => -1 
         [index2] => 78 
         [description] => 12 
        ) 
) 

我需要找出是否有第一級陣列之間的重複。 但只考慮密鑰index1和index2。

在上面的例子中,它應該返回true,因爲0和1具有相同的index1和index2。

回答

1
function hasDupes($array, $delim = '|') { 
    $values = array(); 
    foreach ($array as $v) { 
     $v = $v['index1'] . $delim . $v['index2']; 
     if (isset($values[$v])) { 
      return true; 
     } 
     $values[$v] = 0; 
    } 
    return false; 
} 

無需嵌套循環或在陣列上完成散步(甚至是多次散步),其中btw是大多數建議的array_something函數在內部執行的操作。迭代一次,當你看到一個你以前見過的元素時停止。

+0

應使用的隔板,否則陣列(index1之間=> - 1,索引2 => 77)和陣列(index1之間=> - 17,索引2 => 7)不會工作例如。 – stewe 2012-03-23 22:42:14

+0

@stewe thx,補充。但實際上,分隔符不能是第一個或最後一個字符,否則array(index1 =>' - 1 |',index2 => 77)和array(index1 =>' - 1',index2 =>'| 77')不會工作。無論如何... – rik 2012-03-23 22:58:20

0

不是一個非常高效的算法,但蠻力方式假設外陣列進行數值索引:

function hasDuplicates($array) { 
    $count = count($array); 
    for ($i = 0; $i < $count; $i++){ 
    for ($j = $i+1; $j < $count; j++) { // check every later element in the array 
     if ($array[i]['index1'] == $array[j]['index1'] && $array[i]['index2'] == $array[j]['index2']) { 
     return true; 
     } 
    } 
    } 
    return false; 
} 
2

嘗試這種情況:

<?php 

$a=array(
    array('index1'=>-1,'index2'=>77,'description'=>7), 
    array('index1'=>-1,'index2'=>77,'description'=>5), 
    array('index1'=>-1,'index2'=>78,'description'=>12) 
); 


function check($a){ 
    $data=array(); 

    foreach($a as $arr){ 
     if ($data[$arr['index1'].'|'.$arr['index2']]) { 
      return true; 
     } 
     $data[$arr['index1'].'|'.$arr['index2']]=true; 
    } 
    return false; 
} 

if (check($a)) { 
    echo "duplicates found"; 
}else{ 
    echo "no duplicates"; 
} 

?>