Grouping arrays in PHP

后端 未结 5 993
广开言路
广开言路 2020-12-01 08:22

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

5条回答
  •  一个人的身影
    2020-12-01 08:58

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

提交回复
热议问题