Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Im a bit confuse on how to regroup a array based on a common value. Here is the array below:

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
    )

)

and I would like to group it by its team value like the one below:

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
     )
    )
)

The two main array groups are the teams itself. Any idea/help would be much appreciated. Thanks in advance!

Regards

share|improve this question
add comment

1 Answer

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

Demo

share|improve this answer
    
No need to check with isset, PHP creates it for you if it doesn't exists. –  hakre Oct 31 '11 at 10:38
    
This screams Notice. But PHP5.3 actually doesn't raise one. Didn't know that… - still looks weird, though. –  rodneyrehm Oct 31 '11 at 10:44
    
This does not give notices, see codepad.org/VdoMnfTD, PHP 5.2: ideone.com/vPTKw –  hakre Oct 31 '11 at 10:46
    
thank you for your answers and help! with that small of code, it resolved my issue. Thanks a lot! Im using PHP 5.3.1 so I did not get any notices.. –  Jade Ryan Ibarrola Oct 31 '11 at 10:49
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.