Skip to content

Instantly share code, notes, and snippets.

@datayja
Last active December 16, 2015 09:49
Show Gist options
  • Save datayja/5415556 to your computer and use it in GitHub Desktop.
Save datayja/5415556 to your computer and use it in GitHub Desktop.
Group by operation implemented in PHP on arrays.
<?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