Skip to content

Instantly share code, notes, and snippets.

@MightyPork
Last active February 25, 2018 21:16
Show Gist options
  • Save MightyPork/c9454de7b50cb62eb289 to your computer and use it in GitHub Desktop.
Save MightyPork/c9454de7b50cb62eb289 to your computer and use it in GitHub Desktop.
grouping function
<?php
/**
* Group an array using a callback or each element's property/index
*
* @param array $arr array to group
* @param callable|string $grouper hashing function, or property/index of each item to group by
* @return array grouped
*/
function groupBy(array $arr, $grouper)
{
$first_el = reset($arr);
$is_array = is_array($first_el) || ($first_el instanceof ArrayAccess);
// get real grouper func
$func = is_callable($grouper) ? $grouper : function($x) use ($is_array, $grouper) {
if ($is_array) {
return $x[$grouper];
} else {
return $x->$grouper;
}
};
$grouped = [];
foreach ($arr as $item) {
$hash = $func($item);
if (!isset($grouped[$hash])) {
$grouped[$hash] = [];
}
$grouped[$hash][] = $item;
}
return $grouped;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment