Last active
February 25, 2018 21:16
-
-
Save MightyPork/c9454de7b50cb62eb289 to your computer and use it in GitHub Desktop.
grouping function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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