Top N With Other Grouper
Returns the top N groups and combines remaining groups into Other.
Function signature
ogGroupTopNWithOther(groups = array(), limit = 10)
Categories
- Developer Utilities
Parameters
groupsAssociative counts or rows with label/count keys.limitNumber of top groups to keep.Return value
Short public-safe status message.
- groups
- original_group_count
Compatibility
Existing function name and call order preserved; metadata signature corrected to source.
Minimum PHP version: 7.4
Security notes
Validate request method, identity, permissions, policy arrays, URLs, signatures, and caller-owned allowlists before use; keep secrets and internal paths out of public output.
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Returns the top N groups and rolls the remaining rows into Other.
*
* @param array $groups Associative counts or rows with label/count keys.
* @param int $limit Number of top groups to keep.
* @return array Grouped top-N report.
*/
function ogGroupTopNWithOther($groups = array(), $limit = 10) {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
if (!is_array($groups)) {
$result['message'] = 'Groups must be an array.';
return $result;
}
$limit = (int)$limit;
if ($limit < 1) {
$limit = 10;
}
$rows = array();
foreach ($groups as $key => $value) {
$label = (string)$key;
$count = 0;
if (is_array($value)) {
if (!empty($value['label'])) {
$label = (string)$value['label'];
}
if (!empty($value['count'])) {
$count = (float)$value['count'];
}
} elseif (is_numeric($value)) {
$count = (float)$value;
}
$rows[] = array('label' => $label, 'count' => $count);
}
usort($rows, function($left, $right) {
if ($left['count'] == $right['count']) {
return strcmp($left['label'], $right['label']);
}
if ($left['count'] < $right['count']) {
return 1;
}
return -1;
});
$top = array();
$other_count = 0;
foreach ($rows as $index => $row) {
if ($index < $limit) {
$top[] = $row;
} else {
$other_count += $row['count'];
}
}
if ($other_count > 0) {
$top[] = array('label' => 'Other', 'count' => $other_count);
}
$result['success'] = true;
$result['message'] = 'Top groups built.';
$result['data'] = array('groups' => $top, 'original_group_count' => count($rows));
return $result;
}