3

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.

0

1 Answer 1

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

Demo

Sign up to request clarification or add additional context in comments.

4 Comments

No need to check with isset, PHP creates it for you if it doesn't exists.
This screams Notice. But PHP5.3 actually doesn't raise one. Didn't know that… - still looks weird, though.
This does not give notices, see codepad.org/VdoMnfTD, PHP 5.2: ideone.com/vPTKw
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..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.