2010-05-13 77 views
0

我有一個多維數組,並試圖通過一個鍵的值進行分組。如何使用鍵對多維ARRAY進行SUM和GROUP BY?

所以

Array (
[0] => Array (
     [name] => Edward Foo 
     [desc_topic] => Array (
         [0] => Apple 
         [1] => Banana 
         [2] => Orange 
         )    
     [qtd_posts] => Array (
         [0] => 10 
         [1] => 20 
         [2] => 50 
         ) 

    ) 


[1] => Array (
     [name] => Michael Max 
     [desc_topic] => Array (
         [0] => Apple 
         [1] => Banana 
         [2] => Orange 
         ) 
     [qtd_posts] => Array (
         [0] => 10 
         [1] => 10 
         [2] => 10 
         ) 
    ) 

[2] => Array (
     [name] => Edward Foo 
     [desc_topic] => Array (
         [0] => Apple 
         [1] => Banana 
         [2] => Orange 
         )    
     [qtd_posts] => Array (
         [0] => 5 
         [1] => 10 
         [2] => 30 
         ) 

    ) 

[3] => Array (
     [name] => Michael Max 
     [desc_topic] => Array (
         [0] => Apple 
         [1] => Banana 
         [2] => Orange 
         )    
     [qtd_posts] => Array (
         [0] => 8 
         [1] => 8 
         [2] => 20 
         ) 

    )    

,我真的需要:

Array (
[0] => Array (
     [name] => Edward Foo 
     [desc_topic] => Array (
         [0] => Apple 
         [1] => Banana 
         [2] => Orange 
         )    
     [qtd_posts] => Array (
         [0] => 15 
         [1] => 30 
         [2] => 80 
         ) 

    ) 

[1] => Array (
     [name] => Michael Max 
     [desc_topic] => Array (
         [0] => Apple 
         [1] => Banana 
         [2] => Orange 
         ) 
     [qtd_posts] => Array (
         [0] => 18 
         [1] => 18 
         [2] => 30 
         ) 

      ) 

) 
+0

不知道我得到正確你的問題。 在你的例子中,你想按類型和總和級別進行分組嗎? 所以你想得到: standard = 9(1 + 1 + 7)and premier = 6(3 + 3)? – nico 2010-05-13 14:40:18

+0

我想按名稱和總數「qtd_posts」itens分組。 可以嗎? – Oliveira 2010-05-13 14:54:14

+0

你從數據庫中獲取這些值嗎?因爲在SQL中直接執行它會容易得多。否則,馬克的答案應該做些什麼。 – nico 2010-05-13 15:24:32

回答

1

我假設如下:

  1. 原來的陣列中的每個名稱項具有相同desc_topic子陣列(例如,它們都具有相同的蘋果/香蕉/橙色值,每個實例。
  2. qtd_posts子陣列具有在相同的相應時隙(例如,所有'1'條目將被彙總在一起,所有'2'條目彙總在一起,等等......)
  3. 你想保留父數組鍵,以便所有'Edward Foo'條目將使用第一個鍵一個愛德華符條目(例如0)

如果適用,那麼這樣的事情應該工作:

$newarr = array(); 
$reverse_map = array(); 

foreach($array as $idx => $entry) { 
    if (isset($reverse_map[$entry['name']]) { 
     // have we seen this name before? retrieve its original index value 
     $idx = $reverse_map[$entry['name']]; 
    } else { 
     // nope, new name, so store its index value 
     $reverse_map[$entry['name']] = $idx; 
    } 

    // copy the 'constant' values 
    $newarr[$idx]['name'] = $entry['name']; 
    $newarr[$idx]['desc_top'] = $entry['desc_topic']; 

    // sum the qtd_post values to whatever we previously stored.   
    foreach($entry['qtd_posts'] as $x => $y) { 
     $newarr[$idx]['qtd_posts'][$x] += $y; 
    } 
} 
+0

非常感謝你! 您拯救了我的一天! 我被這個代碼困住了,並不知道如何解決這個阻礙代碼。 – Oliveira 2010-05-13 16:09:40