2011-10-31 211 views
3

我有點混淆瞭如何基於共同的價值重新組合數組。這裏是下面的數組:php多維數組分組

Array 
(
[0] => Array 
    (
      [team] => 1 
      [id] => 5 
      [user] => teamleader1 
      [Designation] => Team Leader 
    ) 
[1] => Array 
    (
     [team] => 1 
     [id] => 6 
     [user] => consultant1 
     [Designation] => Consultant 
    ) 

[2] => Array 
    (
     [team] => 1 
     [id] => 7 
     [user] => consultant2 
     [Designation] => Consultant 
    ) 

[3] => Array 
    (
     [team] => 2 
     [id] => 8 
     [user] => consultant3 
     [Designation] => Consultant 
    ) 

[4] => Array 
    (
     [team] => 2 
     [id] => 9 
     [user] => teamleader2 
     [Designation] => Team Leader 
    ) 

) 

,我想這組由它的團隊價值像下面這樣:

 
Array 
(
[1] => Array 
    (
    [0] => Array(
     [team] => 1 
     [id] => 5 
     [user] =>teamleader1 
     [Designation] => Team Leader 
    ) 
    [1] => Array(
     [team] => 1 
     [id] => 6 
     [user] =>consultant1 
     [Designation] => Consultant 
    ) 
    [2] => Array(
     [team] => 1 
     [id] => 7 
     [user] =>consultant2 
     [Designation] => Consultant 
    ) 
) 
[2] => Array 
    (
    [0] => Array(
     [team] => 1 
     [id] => 8 
     [user] =>consultant3 
     [Designation] => Consultant 
    ) 
    [1] => Array(
     [team] => 1 
     [id] => 9 
     [user] =>teamleader2 
     [Designation] => Team Leader 
    ) 
    ) 
) 

兩個主要的陣列組是球隊本身。任何想法/幫助將不勝感激。提前致謝!

問候

回答

2
<?php 
$grouped = array(); 
foreach ($yourData as $item) { 
    // copy item to grouped 
    $grouped[$item['team']][] = $item; 
} 
var_dump($grouped); 

Demo

+0

不需要檢查與isset,PHP創建它適合你,如果不存在的話。 – hakre

+0

這個尖叫聲。但是PHP5.3實際上並沒有提出一個。不知道... - 雖然看起來很奇怪。 – rodneyrehm

+0

這不會給出通知,請參閱http://codepad.org/VdoMnfTD,PHP 5.2:http://ideone.com/vPTKw – hakre