2012-03-20 73 views
0

我有以下兩個數組:比較兩個數組和列表的普通表項

userStatus 
--------------- 
Array 
(
    [0] => Array 
     (  
      [Username] => [email protected] 
      [Status] => Active 
     ) 

    [1] => Array 
     (   
      [Username] => [email protected] 
      [Status] => Terminated 
     ) 

    [2] => Array 
     (   
      [Username] => [email protected] 
      [Status] => OnVacation 
     ) 
) 

users 
------ 
Array 
(
    [0] => [email protected] 
    [1] => [email protected] 
    [2] => [email protected] 
) 

我想寫的是帶來了在用戶陣列匹配用戶名欄中,所有userStatus項的數組的一個片段。

我可以通過雙循環運行和比較兩個數組來實現這一點,但是有沒有一種使用PHP內置數組函數或任何其他方式來做到這一點的快速方法?

+0

你看過array_filter()或array_map()函數嗎? – 2012-03-20 06:49:08

+1

這裏有'array_intersect'這個東西'http://www.php.net/manual/en/function.array-intersect.php – Rafee 2012-03-20 07:08:26

回答

-1

如果你想讓它快速,設置用戶數組是這樣的:

$users = array(
    '[email protected]' => 1, 
    '[email protected]' => 1, 
    '[email protected]' => 1 
); 

然後,只需檢查數組索引設置:

$matched = array(); 
foreach($userStatus as $k => $v) { 
    if(isset($users[$v['Username']])) { 
     $matched[$k] = $v; 
    } 
} 

輸出:

foreach($matched as $k => $v) { 
    echo "$k = ".$v['Username']." is ".$v['Status']."<br>"; 
} 
+0

你可以在這裏看到它:http://farhanjiwani.com/stackOverflow/9782435/ – AlfaTrion 2012-03-20 07:06:03

0

如果你使用PHP> = 5.3,那麼你可以使用array_filter匿名回調函數...不是特別有效,但很簡單。

$userStatus=array(
     array(
      'Username' => '[email protected]', 
      'Status' => 'Active' 
     ), 
     array(
      'Username' => '[email protected]', 
      'Status' => 'Terminated' 
     ), 
     array(
      'Username' => '[email protected]', 
      'Status' => 'OnVacation' 
     )); 

$users = array(
    '[email protected]est.net', 
    '[email protected]', 
    '[email protected]' 
); 


$filtered = array_filter($userStatus, function ($var) { 
global $users; 
return in_array($var['Username'], $users); 
}); 

print_r($filtered); 

如果你的東西后,再快一點的時候,那麼用戶數組轉換成「地圖」,通過改變值的鍵,然後檢查是否有鍵在回調設置。

$userlookup = array_flip($users); 

$filtered = array_filter($userStatus, function ($var) { 
global $userlookup; 
return isset($userlookup[$var['Username']]); 
});