2011-10-22 23 views
0

關於數組的PHP問題。假設我們有兩個數組:結合並消除數組中的鍵值對

[first] => Array 
    (
     [0] => users 
     [1] => posts 
     [2] => comments 
    ) 

[second] => Array 
    (
     [users] => the_users 
     [posts] => the_posts 
     [comments] => the_comments 
     [options] => the_options 
    ) 

如何比較這兩個數組?意思是,我們如何在以某種方式組合它們(array_merge?)後檢查第一個數組中的值是否等於第二個數組中的鍵(array_flip?)。無論哪個值/密鑰對匹配,將它們從數組中移除。

基本上,最終結果將是兩個陣列組合,重複去除,並且唯一的索引將是:

[third] => Array 
    (
     [options] => the_options 
    ) 

回答

3

試試這個:

$third = array_diff_key($second,array_flip($first)); 
+0

Ahhhhh! array_diff_key正是我想要的。非常感謝Vik。 – mousesports

0

有可能是這個內置功能,但如果不存在嘗試:

$third = array(); 
foreach(array_keys($second) as $item) 
    if(!in_array($item, $first)) 
    $third[$item] = $second[$item]; 

注意,這個假設$first不會有不有$second相應的鍵的項目。爲了解決這個問題,你可以有一個額外的循環(我不知道你會在$third將該值設置爲這些,也許null

foreach($first as $item) 
    if(!in_array($item, array_keys($second))) 
    $third[$item] = null; 
+0

是的,要問是否有內置函數。我做了一些與你的第二個foreach非常相似的東西,它工作得很好。想知道是否有另一種方式做,但謝謝老兄:) – mousesports

+0

好的,感謝您的編輯。您剛剛添加的第二個foreach對於我目前想要做的事情來說是不必要的 - 但是,毫無疑問,它將在未來有用。 – mousesports

+0

根據你的2個答案,這至多是O(n^k)或O(n^2),當你可以在O(n)時間內完成時,這是非常糟糕的。當你可以數到1000時,等於計數到1,000,000。 – evan

0

這很簡單,而且這種方式是非常有效的:

$third = $second; 

foreach($first as $value) 
{ 
    if (isset($third[$value])) 
    { 
     unset($third[$value]); 
    } 
} 
0

這就是答案,以烏爾問題

$first= array 
(
    "0" => "users", 
    "1" => "posts", 
    "2" => "comments" 
); 
$firstf=array_flip($first); 
$second = array 
(
    "users" => "the_users", 
    "posts" => "the_posts", 
    "comments" => "the_comments", 
    "options" => "the_options" 
); 
$third=array_diff_key($second,$firstf); 
print_r($third);