2013-11-20 13 views
0

第一次海報,長期訪問者。過濾PHP數組,用於多個選擇,其中子數組項相等

我試過找到可以幫助我的東西,但到目前爲止,我一直不成功。如果有人知道這個問題的重複,我提前道歉,無法找到它。

無論如何,我想知道是否有任何最佳實踐或對我的問題很好的解決方案。這並不是說我不能寫一個功能正常的代碼,我只是不想每次重寫輪子,希望有一個優雅的解決方案。

考慮以下的數組:

Array 
(
    [0] => Array 
     (
      [filename] => 'test1.jpg' 
      [comment] => 'This is a test' 
      [status] => 2 
      [author] => 'John Smith' 
      [uniquekey1] => 3 
     ) 

    [1] => Array 
     (
      [filename] => 'test2.jpg' 
      [comment] => 'This is a test' 
      [status] => 2 
      [author] => 'Unknown' 
      [uniquekey2] => 3 
     ) 

    [2] => Array 
     (
      [filename] => 'test3.jpg' 
      [comment] => 'This is a test' 
      [status] => 2 
      [author] => 'Unknown' 
      [uniquekey3] => 3 
     ) 
) 

處理此之後,我想數組返回包含從陣列的陣列上方的鍵,但只從處於相同的鍵的鍵和值所有的子陣列。實際上,上述的將產生的陣列看起來像這樣:

Array 
(
    [comment] => 'This is a test' 
    [status] => 2 
) 

作爲清晰可見,只有密鑰:即在所有三個相同的(在這個例子中)返回數組項值對。

一個很好的使用示例是在iTunes中編輯多個項目,其中相同的值顯示在編輯字段中,其餘顯示幻影「多值」文本。我正在瞄準類似的東西。

感謝您的幫助和指點。

編輯:此處也添加了解決方案。由於接受的解決方案錯過了'uniqueKey'不相同,並且array_intersect()在值匹配時也返回了這些,這是不必要的行爲,所以有點混淆。看來,解決方案是使用array_intersect_assoc()。

$a = array(
    array(
     'filename' => 'test1.jpg', 
     'comment' => 'This is a test', 
     'status' => 2, 
     'author' => 'John Smith', 
     'uniquekey1' => 3 
    ), 
    array(
     'filename' => 'test2.jpg', 
     'comment' => 'This is a test', 
     'status' => 2, 
     'author' => 'Unknown', 
     'uniquekey2' => 3 
    ), 
    array(
     'filename' => 'test3.jpg', 
     'comment' => 'This is a test', 
     'status' => 2, 
     'author' => 'Unknown', 
     'uniquekey3' => 3 
    ), 
); 

$b = call_user_func_array('array_intersect_assoc',$a); 

...看起來返回「評論」和「狀態」字段,而不是其他。

回答

0

Array_intersect救援:

$array = array(); 
$array[] = array('filename' => 'test1.jpg', 'comment' => 'This is a test', 'uniqueKey' => 3); 
$array[] = array('filename' => 'test2.jpg', 'comment' => 'This is a test', 'uniqueKey' => 3); 
$array[] = array('filename' => 'test3.jpg', 'comment' => 'This is a test', 'uniqueKey' => 3); 

$intersection = call_user_func_array('array_intersect', $array); 

$交集則是:

Array 
(
    [comment] => This is a test 
    [uniqueKey] => 3 
) 
+0

啊,但有問題的,因爲我一直在尋找在這裏:http://stackoverflow.com/questions/9438057/array-intersect-but-for-a-sub-arrays-of-a-array-variable ...並基本找到相同的解決方案。但是,如果仔細觀察,「uniqueKey」是不同的,不應匹配並返回。 我一直在思考array_intersect_ukey的問題,但還沒有嘗試過(現在就開始工作)。 – Bornhall

+0

好的,解決方法是使用array_intersect_assoc來代替,至少它看起來像它的工作:) – Bornhall