PHP 中的数组分组 [英] Grouping arrays in PHP

查看:34
本文介绍了PHP 中的数组分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 200 个项目的数组.我想输出数组,但将具有共同值的项目分组.类似于 SQL 的 GROUP BY 方法.这应该相对容易做到,但我还需要对组项目进行计数.

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.

我可以将结果转储到 Lucene 或 sqlite 之类的东西中,然后在每次加载页面时对该文档运行查询吗?

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.

推荐答案

只需遍历数组并为组使用另一个数组.它应该足够快,并且可能比使用 sqlite 或类似工具时所涉及的开销更快.

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;
    }
}

这篇关于PHP 中的数组分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆