Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping arrays in PHP

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.

like image 368
GivP Avatar asked Jun 11 '09 17:06

GivP


People also ask

What is array grouping?

The group() method groups the elements of the calling array according to the string values returned by a provided testing function. The returned object has separate properties for each group, containing arrays with the elements in the group. This method should be used when group names can be represented by strings.

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

What does array [] mean in PHP?

Arrays ¶ An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.


1 Answers

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;
    }
}
like image 180
Ferdinand Beyer Avatar answered Oct 21 '22 02:10

Ferdinand Beyer