Skip to content

Instantly share code, notes, and snippets.

@rohjay
Last active March 13, 2016 21:11
Show Gist options
  • Save rohjay/b34bf24a539c6061c3f4 to your computer and use it in GitHub Desktop.
Save rohjay/b34bf24a539c6061c3f4 to your computer and use it in GitHub Desktop.
php function to group a list of dictionaries by a common key.
<?php
// I find myself grouping a lot of data... heres a quick helper function to do just that =]
function grouper($data, $key_to_group_by, $key_to_group_unfound='unfound', $unset_key_from_data=false) {
$grouped_results = array();
foreach ( $data as $k => $value ) {
$value_key = isset($value[$key_to_group_by]) ? $value[$key_to_group_by] : $key_to_group_unfound;
if ( !isset($grouped_results[$value_key]) ) {
$grouped_results[$value_key] = array();
}
if ( $unset_key_from_data == true && $value_key !== $key_to_group_unfound ) {
unset($value[$key_to_group_by]);
}
$grouped_results[$value_key][] = $value;
}
return $grouped_results;
}
/*
Example:
$dataset = array(
array(
'name' => 'Robin',
'favorite_color' => 'red',
'more_data' => 'some'
),
array(
'name' => 'Jason',
'favorite_color' => 'orange',
'more_data' => 'other'
),
array(
'name' => 'Cody',
'favorite_color' => 'red',
'more_data' => 'piece'
),
array(
'name' => 'Shelly',
'favorite_color' => 'yellow',
'more_data' => 'of'
),
array(
'name' => 'Jessica',
'favorite_color' => 'orange',
'more_data' => 'random'
),
array(
'name' => 'Matt',
'favorite_color' => 'yellow',
'more_data' => 'data'
),
array(
'name' => 'Rachel',
'favorite_color' => 'orange',
'more_data' => 'that'
),
array(
'name' => 'Jessica',
'favorite_color' => 'red',
'more_data' => 'doesnt matter'
),
);
$results = grouper($test_data['dataset'], $test_data['key']);
print_r($results);
Array
(
[red] => Array
(
[0] => Array
(
[name] => Robin
[favorite_color] => red
[more_data] => some
)
[1] => Array
(
[name] => Cody
[favorite_color] => red
[more_data] => piece
)
[2] => Array
(
[name] => Jessica
[favorite_color] => red
[more_data] => doesnt matter
)
)
[orange] => Array
(
[0] => Array
(
[name] => Jason
[favorite_color] => orange
[more_data] => other
)
[1] => Array
(
[name] => Jessica
[favorite_color] => orange
[more_data] => random
)
[2] => Array
(
[name] => Rachel
[favorite_color] => orange
[more_data] => that
)
)
[yellow] => Array
(
[0] => Array
(
[name] => Shelly
[favorite_color] => yellow
[more_data] => of
)
[1] => Array
(
[name] => Matt
[favorite_color] => yellow
[more_data] => data
)
)
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment