Page MenuHomePhorge

function mgroup($list, $by, ...)
libphutil Technical Documentation (Core Utilities)

Group a list of objects by the result of some method, similar to how GROUP BY works in an SQL query. This function simplifies grouping objects by some property:

$animals_by_species = array();
foreach ($animals as $animal) {
  $animals_by_species[$animal->getSpecies()][] = $animal;
}

This can be expressed more tersely with mgroup():

$animals_by_species = mgroup($animals, 'getSpecies');

In either case, the result is a dictionary which maps species (e.g., like "dog") to lists of animals with that property, so all the dogs are grouped together and all the cats are grouped together, or whatever super businessesey thing is actually happening in your problem domain.

See also igroup(), which works the same way but operates on array indexes.

Parameters
list$listList of objects to group by some property.
string$byName of a method, like 'getType', to call on each object in order to determine which group it should be placed into.
...Zero or more additional method names, to subgroup the groups.
Return
dictDictionary mapping distinct method returns to lists of all objects which returned that value.