views:

775

answers:

4

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 prehaps dump the results into something like Lucene or sqlite then run a query on that document on each page load?

Any thoughts would be greatly appreciated.

+5  A: 
$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";
chaos
+1  A: 

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;
    }
}
Ferdinand Beyer
+1  A: 

Here's a quick example:

$a = array(1, 2, 3, 1, 2, 3, 3, 2, 3, 2, 3, 4, 4, 1);
$n = array_count_values($a);
arsort($n);

print_r($n);

Array ( [3] => 5 [2] => 4 [1] => 3 [4] => 2 )

simplemotives
A: 

Thanks a lot,... a great post resource,... Very helpful,...