Grouping arrays in PHP

后端 未结 5 984
广开言路
广开言路 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

    $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";
    

提交回复
热议问题