2012-08-12 101 views
2

我的人一個數組,看起來像這樣:計數的值在一個陣列出現在另一個陣列的出現

$people = 
    Array 
    (
     [0] => Array 
      (
       [email] => [email protected] 
       [name] => Name Surname 
       [count] => 0 
      ) 

     [1] => Array 
      (
       [email] => [email protected] 
       [name] => Name2 Surname 
       [count] => 0 
      ) 
    ) 

而且我有一個數組這是一個MySQL查詢,查找的結果像這樣:

$query= 
    Array 
    (
     [0] => Array 
      (
       [email] => [email protected] 
       [name] => Name Surname 
      ) 

     [1] => Array 
      (
       [email] => [email protected] 
       [name] => Name2 Surname 
      ) 

     [2] => Array 
      (
       [email] => [email protected] 
       [name] => Name Surname 
      ) 

    ) 

對於$每個人的e-mail地址,我想$people['count']等於該E-mail地址在$查詢多少次發生。

我試過的方式來做到這一點的負載,而且我不太得到期望的結果。

爲免生疑問,我的最終結果根據上面的例子應該是這樣的:

$people = 
    Array 
    (
     [0] => Array 
      (
       [email] => [email protected] 
       [name] => Name Surname 
       [count] => 2 
      ) 

     [1] => Array 
      (
       [email] => [email protected] 
       [name] => Name2 Surname 
       [count] => 1 
      ) 
    ) 
+1

其中是您檢查重複值的代碼。 – greatmajestics 2012-08-12 11:36:49

+2

您可以直接從數據庫中選擇計數的電子郵件嗎?類似這樣的: 'SELECT count(*)FROM table WHERE email IN('[email protected]','[email protected]')GROUP BY email'? – 2012-08-12 11:37:46

+0

我明白你在說什麼,但在這個特殊情況下,這兩者都沒有用。數組實際上包含比上面顯示的更多的信息,因此重複值不是問題。至於MySQL查詢,每個數組可能包含數百個項目,因此任何額外的查詢都不是最佳的。感謝您花時間評論 – SpongeBobPHPPants 2012-08-12 11:41:59

回答

4
foreach ($people as $key => $man) { // iterating through each man 
    $_occurences = 0; 

    foreach ($query as $_item) // iterating through each result in the result set 
    if ($_item['email'] == $man['email']) // comparing current man to each result item 
     $_occurences ++; 

    $people[$key]['count'] = $_occurences; // saving number of occurrences in the `count` key 

} 

UPD:還有一個解決方案使用array_maparray_reduce和漂亮ternary運營商。它比foreach慢,但緊湊和專業兩倍。

它是較慢的(在性能方面)BEC。的函數調用開銷,但是對於「小」的迭代量,這個下降是微不足道的。它將更新$people數組而不重新分配它。我們通過引用傳遞每個&$man

array_map(function (&$man) use ($query) { 
    $man['count'] = array_reduce($query, function ($count, $row) use ($man) { 
     return ($row['email'] === $man['email']) ? ++$count : $count ; 
    }, 0); 
}, $people); 
+1

就是這樣 - 非常感謝您。得到了我需要的答案,並在下一次學到了新的東西。幹得好,謝謝你的快速回復。 – SpongeBobPHPPants 2012-08-12 11:50:01

+0

@PHPNewbDeem,不客氣! – 2012-08-12 11:53:17

1

不知道如果這就是你所需要的東西,但你可以改變你正在運行的查詢:

SELECT COUNT(name) as cnt, name,email FROM table_name GROUP BY name; 

然後$query陣列看起來像:

$query= 
    Array 
    (
     [0] => Array 
      (
       [email] => [email protected] 
       [name] => Name Surname 
       [cnt] => 2 
      ) 

     [1] => Array 
      (
       [email] => [email protected] 
       [name] => Name2 Surname 
       [cnt] => 1 
      )     
    ) 

然後您可以在陣列上運行並獲取$query陣列中每個項目的cnt

+0

謝謝,很好的答案。正在尋找更多的PHP方法來做到這一點,@Paul T. Rawkeen得到了我期待的解決方案。 – SpongeBobPHPPants 2012-08-12 12:04:34