phparraysmultidimensional-arraygroupingsub-array

Group rows of a 2d array by a specified column and push rows into subarrays


I'm a bit confused on how to regroup an 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.


Solution

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

    Demo