Created
October 9, 2013 11:08
-
-
Save jrivero/6899595 to your computer and use it in GitHub Desktop.
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 $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