在PHP分组阵列 [英] Grouping arrays in 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.
我可以prehaps结果转储成类似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?
任何想法,将大大AP preciated。
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屋!