Skip to content

Instantly share code, notes, and snippets.

@jrivero
Created October 9, 2013 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrivero/6899595 to your computer and use it in GitHub Desktop.
Save jrivero/6899595 to your computer and use it in GitHub Desktop.
<?php
function array_group_by(array $array, callable $key_selector)
{
$result = [];
foreach ($array as $values) {
$key = call_user_func($key_selector, $values);
$result[$key][] = $values;
}
return $result;
}
// Example
$data = array(
[1, "A", "AA"],
[1, "A", "BB"],
[1, "A", "CC"],
[2, "B", "AA"],
[2, "B", "BB"],
[3, "C", "AA"],
);
$grouped = array_group_by($data, function($row) { return $row[0]; });
print_r($grouped);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment