Group rows in a 2d array and count number of rows in each respective group
Asked Answered
G

5

13

I have an array of 200 items. I would like to output the array but group the items with a common value. Similar to SQL's GROUP BY method. This should be relatively easy to do but I also need a count for the group items.

Does anyone have an efficient way of doing this? This will happen on every page load so I need it to be fast and scalable.

Could I perhaps dump the results into something like Lucene or SQLite then run a query on that document on each page load?

Gilgilba answered 11/6, 2009 at 17:2 Comment(3)
Lucene or sqlite are most likely much more inefficient than a PHP solution.Sextet
Check this one out : there should be solve your problem simply pastebin.com/UJAqnKSsZelazny
This question is missing its minimal reproducible example.Cockayne
S
30

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,
        );
    } else {
        $groups[$key]['items'][] = $item;
        $groups[$key]['count'] += 1;
    }
}
Shortridge answered 11/6, 2009 at 17:7 Comment(2)
sql servers do it faster most of the timeLoutish
isset is very important. that's what i missedMillwater
L
14
$groups = array();
foreach($items as $item)
    $groups[$item['value']][] = $item;
foreach($groups as $value => $items)
    echo 'Group ' . $value . ' has ' . count($items) . ' ' . (count($items) == 1 ? 'item' : 'items') . "\n";
Lasso answered 11/6, 2009 at 17:7 Comment(0)
A
2
$aA = array_count_values(array(1,2,3,4,5,1,2,3,4,5,6,1,1,1,2,2));
$aB = array();
foreach($aA as $index=>$aux){
     array_push($aB,$index);
}
print_r($aB);

Result:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) 
Alex answered 14/9, 2012 at 13:5 Comment(1)
The sample data in this unexplained answer does not resemble the data structure that would be returned from a SQL result. This answer is grouping flat data and producing a flat array of counts. On top of that, this snippet is over engineered for the output that it produces -- the whole snippet can be very simply replaced with array_unique().Cockayne
C
0

Without sample data (a minimal, clear verifiable example) in the question it is difficult to confidently give precise advice on the best way(s) to perform the task. One way is to use temporary grouping keys in the result array. Store an encountered whole row and an appended count element in the result array if the identifying key hadn't been encountered before. The appended element should have a value of 0. Then unconditionally increment the count value. When the loop is finished, if you don't want the grouping keys, you can call array_values().

Code: (Demo)

$result = [];
foreach ($array as $row) {
    $result[$row['group']] ??= $row + ['count' => 0]; // only save 1st of group with 0 count
    ++$result[$row['group']]['count']; // increment the count
}
var_export(array_values($result));
Cockayne answered 16/4, 2023 at 1:46 Comment(0)
P
-1
"$Switches" Array with [3] elements
0       
    SwitchID    1   
    name    k�  
    type    output  
    displayAs   button  
    value   on  
    groupname   group1  
1   Array [6]   
2   Array [6]   


// this will sort after groupname

$result = array();
$target = count($Switches);
for($i=0;$i<$target;$i++)
{
    $groupname = $Switches[$i]["groupname"];

    $result[$groupname][] = $Switches[$i];
}

// count amount of groups
$groupCount = count($result);

... or did i miss something?

Pitiful answered 28/5, 2013 at 23:12 Comment(1)
I think this answer is missing clarity / explanation.Cockayne

© 2022 - 2024 — McMap. All rights reserved.