2009-06-11 60 views
12

我有一個包含200個項目的數組。我想輸出數組,但將這些項目用一個公共值分組。類似於SQL的GROUP BY方法。這應該相對容易做到,但我也需要爲組項目計數。在PHP中分組數組

有沒有人有這樣做的有效方式?這將發生在每個頁面加載,所以我需要它快速和可擴展。

我可以預先將結果轉儲爲類似Lucene或sqlite的結果,然後在每個頁面加載上對該文檔運行查詢嗎?

任何想法將不勝感激。

+3

Lucene或sqlite最可能比PHP解決方案效率低得多。 – 2009-06-11 17:05:45

+0

檢查這一個:應該有解決你的問題簡單 http://pastebin.com/UJAqnKSs – eric 2014-04-04 16:13:23

回答

30

只是迭代數組並使用另一個數組作爲組。它應該足夠快,可能比使用sqlite或類似的開銷更快。

$groups = array(); 
foreach ($data as $item) { 
    $key = $item['key_to_group']; 
    if (!isset($groups[$key])) { 
     $groups[$key] = array(
      'items' => array($item), 
      'count' => 1, 
     ); 
    } else { 
     $groups[$key]['items'][] = $item; 
     $groups[$key]['count'] += 1; 
    } 
} 
+0

sql服務器做大部分時間更快 – GorillaApe 2012-05-01 00:17:46

14
$groups = array(); 
foreach($items as $item) 
    $groups[$item['value']][] = $item; 
foreach($groups as $value => $items) 
    echo 'Group ' . $value . ' has ' . count($items) . ' ' . (count($items) == 1 ? 'item' : 'items') . "\n"; 
3

這裏有一個簡單的例子:

$a = array(1, 2, 3, 1, 2, 3, 3, 2, 3, 2, 3, 4, 4, 1); 
$n = array_count_values($a); 
arsort($n); 

的print_r($ N);

陣列( [3] => 5 [2] => 4 [1] => 3 [4] => 2)

3
$aA = array_count_values(array(1,2,3,4,5,1,2,3,4,5,6,1,1,1,2,2)); 
$aB = array(); 
foreach($aA as $index=>$aux){ 
    array_push($aB,$index); 
} 
print_r($aB); 

結果:

Array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6) 
0
"$Switches" Array with [3] elements 
0  
    SwitchID 1 
    name k� 
    type output 
    displayAs button 
    value on 
    groupname group1 
1 Array [6] 
2 Array [6] 


// this will sort after groupname 

$result = array(); 
$target = count($Switches); 
for($i=0;$i<$target;$i++) 
{ 
    $groupname = $Switches[$i]["groupname"]; 

    $result[$groupname][] = $Switches[$i]; 
} 

// count amount of groups 
$groupCount = count($result); 

...還是我錯過了什麼?