Group subarrays by one column, make comma-separated values from other column within groups

There should be more elegant solutions, but simplest one I can think of would be this. // The data you have pasted in the question $data = []; $groups = []; // Go through the entire array $data foreach($data as $item){ // If the key doesn’t exist in the new array yet, add it if(!array_key_exists($item[1], … Read more

Identify groups of consecutive numbers in a list

EDIT 2: To answer the OP new requirement ranges = [] for key, group in groupby(enumerate(data), lambda (index, item): index – item): group = map(itemgetter(1), group) if len(group) > 1: ranges.append(xrange(group[0], group[-1])) else: ranges.append(group[0]) Output: [xrange(2, 5), xrange(12, 17), 20] You can replace xrange with range or any other custom class. Python docs have a … Read more

Grouping Python tuple list

itertools.groupby can do what you want: import itertools import operator L = [(‘grape’, 100), (‘grape’, 3), (‘apple’, 15), (‘apple’, 10), (‘apple’, 4), (‘banana’, 3)] def accumulate(l): it = itertools.groupby(l, operator.itemgetter(0)) for key, subiter in it: yield key, sum(item[1] for item in subiter) print(list(accumulate(L))) # [(‘grape’, 103), (‘apple’, 29), (‘banana’, 3)]

Merge arrays of associative arrays by shared column values

you can try array_reduce: $someVariable=”someValue”; $result = array_reduce(array_merge($array1, $array2), function ($carry, $item) use ($someVariable) { if (isset($carry[$item[‘category_id’]])) { $carry[$item[‘category_id’]] = array_merge($carry[$item[‘category_id’]], $item); } else { $carry[$item[‘category_id’]] = $item; } return $carry; }, array()); var_dump($result);

Group multidimensional array data based on two column values and sum values of one column in each group

This function should do the job. function groupByPartAndType($input) { $output = Array(); foreach($input as $value) { $output_element = &$output[$value[‘part’] . “_” . $value[‘type’]]; $output_element[‘part’] = $value[‘part’]; $output_element[‘type’] = $value[‘type’]; !isset($output_element[‘count’]) && $output_element[‘count’] = 0; $output_element[‘count’] += $value[‘count’]; } return array_values($output); } If both databases are on the same database server you would be able to … Read more