2011-07-22 73 views
0

有在PHP下面的兩個不同的陣列:檢查陣列1的值數組2

Array1 
(
    [0] => Array 
     (
      [id] => 1 
      [name] => William 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [name] => Bob 
     ) 

    [2] => Array 
     (
      [id] => 3 
      [name] => Michael 
     ) 

) 
Array2 
(
    [0] => Array 
     (
      [id] => 11128 
      [name] => John 
     ) 

    [1] => Array 
     (
      [id] => 11127 
      [name] => Adam 
     ) 

    [2] => Array 
     (
      [id] => 11126 
      [name] => Andrew 
     ) 

    [3] => Array 
     (
      [id] => 11125 
      [name] => William 
     ) 

    [4] => Array 
     (
      [id] => 11124 
      [name] => Bob 
     ) 

) 

我能以某種方式找到匹配name這麼輸出將是這樣的:

Array1 (1, id:2) matches Array2 (4, id:11124) with name: Bob 
Array1 (0, id:1) matches Array2 (3, id:11125) with name: William 

對不起,如果它是不清楚

回答

3

你可以隨時嘗試一個簡單的foreach循環:

<?php 
foreach($array1 as $key1=>$value1) { 
    foreach($array2 as $key2=>$value2) { 
     if($value1['name'] === $value2['name']) { 
      sprintf('Array1 (%d, id:%d) matches Array2 (%d, id:%d) with name: %s', $key1, $value1['id'], $key2, $value2['id'], $value1['name']); 
     } 
    } 
} 
?> 
+1

+1'sprintf' –

1
foreach($array1 as $i=>$x){ 
    foreach($array2 as $k=>$y){ 
    if($x['name'] == $y['name']){ 
     echo "Array1 ($i, id:{$x['id']}) matches Array2 ($k, id:{$y['id']}) with name: {$x['name']}\n"; 
     break; 
    } 
    } 
} 
+1

+1我們有除了sprintf的VS回聲相同的代碼! –

+0

@PhpMyCoder:我在echo :-P –

+0

以及一個空的結果數組之後有一個'break'。我認爲如果你在其中存儲了匹配,然後將它們映射到'vsprintf',你可能會超過我。 –