2011-04-26 91 views
0

我想幫助完成我的函數,比較兩個數組並返回兩者中相同的元素的值。比較動態數組

$array1 = array("bob","mike","david","gary"); 
$array2 = array("susan","jenny","mike"); 

這兩個數組每次都會有不同數量的元素。我運行下面的功能,它說有匹配,但不會告訴我哪些。如果數組沒有相同數量的元素,我的函數也會工作嗎?

echo find_matches($array1,$array2); 


function find_matches($mac1, $mac2){ 

    $matches = array(); 

    foreach($mac1 as $mac){ 
     if(in_array($mac, $mac2)){ 
      $matches[] = $mac; 
     } 
    } 

    if ($matches != 0){ 

    $error_message = "The following numbers match: " . implode(' ', $matches); 

    return $error_message; 
    }else{ 
    return true; 
    } 
} 
+1

你難道不想說「如果(計數($比賽)> 0 ){「走到最後?我的PHP很生鏽。除此之外,我認爲你的邏輯應該適當地比較不同大小的數組。 – Marvo 2011-04-26 17:48:06

+0

[Compare 2 arrays for likeness]的可能的重複(http://stackoverflow.com/questions/4065431/compare-2-arrays-for-likeness) – webbiedave 2011-04-26 17:57:38

+0

你相信你在比較之前使用count()是正確的。謝謝! – Denoteone 2011-04-26 17:57:42

回答

10

如果你正在尋找返回匹配的匹配數量和自己,你可以使用array_intersect

$matches = array_intersect($array1, $array2); 
+1

那麼有2個小時我永遠不會回來。謝謝。 – Denoteone 2011-04-26 17:55:18