Last active
December 16, 2015 09:49
-
-
Save datayja/5415556 to your computer and use it in GitHub Desktop.
Group by operation implemented in PHP on arrays.
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 | |
function array_group_by (array $array, callable $mapping) | |
{ | |
$buckets = []; | |
foreach ($array as $item) { | |
$key = $mapping($item); | |
if (!isset($buckets[$key])) { | |
$buckets[$key] = [$item]; | |
} else { | |
$buckets[$key][] = $item; | |
} | |
} | |
return $buckets; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment