Grouping arrays in PHP

Just iterate over the array and use another array for the groups. It should be fast enough and is probably faster than the overhead involved when using sqlite or similar. $groups = array(); foreach ($data as $item) { $key = $item[‘key_to_group’]; if (!isset($groups[$key])) { $groups[$key] = array( ‘items’ => array($item), ‘count’ => 1, ); } … Read more

Chunk and transpose a flat array into rows with a specific number of columns

Use array_chunk() to break the array up in to $cols: $chunks = array_chunk($array, ceil(count($array) / $cols)); Which would give you: array(array(‘A’, ‘B’, ‘C’, ‘D’), array(‘E’, ‘F’, ‘G’)); Then combine the values from each array where the keys match. array_unshift($chunks, null); $chunks = call_user_func_array(‘array_map’, $chunks); // array(array(‘A’, ‘E’), array(‘B’, ‘F’), array(‘C’, ‘G’), array(‘D’, NULL)) Here’s an … Read more

Group 2d array rows by one column and sum another column [duplicate]

Let’s pretend that $array contains our data. We will go through the array and continually add the time_spent to another array keyed by url_id. $ts_by_url = array(); foreach($array as $data) { if(!array_key_exists($data[‘url_id’], $ts_by_url)) $ts_by_url[ $data[‘url_id’] ] = 0; $ts_by_url[ $data[‘url_id’] ] += $data[‘time_spent’]; } $ts_by_url should now contain: 2191238 => 41 2191606 => 240 // … Read more

How to do range grouping on a column using dplyr?

We can use cut to do the grouping. We create the ‘gr’ column within the group_by, use summarise to create the number of elements in each group (n()), and order the output (arrange) based on ‘gr’. library(dplyr) DT %>% group_by(gr=cut(B, breaks= seq(0, 1, by = 0.05)) ) %>% summarise(n= n()) %>% arrange(as.numeric(gr)) As the initial … Read more

SVG Positioning

Everything in the g element is positioned relative to the current transform matrix. To move the content, just put the transformation in the g element: <g transform=”translate(20,2.5) rotate(10)”> <rect x=”0″ y=”0″ width=”60″ height=”10″/> </g> Links: Example from the SVG 1.1 spec

Grouping by object value, counting and then setting group key by maximum object attribute

Here’s one approach. First group into lists and then process the lists into the values you actually want: import static java.util.Comparator.comparingLong; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toMap; Map<Route,Integer> routeCounts = routes.stream() .collect(groupingBy(x -> x)) .values().stream() .collect(toMap( lst -> lst.stream().max(comparingLong(Route::getLastUpdated)).get(), List::size ));