Skip to content

Instantly share code, notes, and snippets.

@k-hamada
Created December 21, 2013 14:37
Show Gist options
  • Save k-hamada/8070126 to your computer and use it in GitHub Desktop.
Save k-hamada/8070126 to your computer and use it in GitHub Desktop.
$array = array(
array('id' => 'a', 'value' => 11),
array('id' => 'b', 'value' => 12),
array('id' => 'c', 'value' => 13),
array('id' => 'a', 'value' => 21),
array('id' => 'b', 'value' => 22),
array('id' => 'b', 'value' => 32),
);
var_dump(
array_reduce($array, function ($result, $item) {
$result[$item['id']][] = $item;
return $result;
}, array())
);
/*
array(3) {
["a"]=> array(2) {
[0]=> array(2) { ["id"]=> string(1) "a" ["value"]=> int(11) }
[1]=> array(2) { ["id"]=> string(1) "a" ["value"]=> int(21) }
}
["b"]=> array(3) {
[0]=> array(2) { ["id"]=> string(1) "b" ["value"]=> int(12) }
[1]=> array(2) { ["id"]=> string(1) "b" ["value"]=> int(22) }
[2]=> array(2) { ["id"]=> string(1) "b" ["value"]=> int(32) }
}
["c"]=> array(1) {
[0]=> array(2) { ["id"]=> string(1) "c" ["value"]=> int(13) }
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment