my @items; my $last_key; while ($row = $sth->fetch_hashref()) { if (!@items || $last_key != $row->{item_key}) { push @items, { item_key => $row->{item_key}, item_description => $row->{item_description}, item_summary => $row->{item_summary}, actions => [], }; $last_key = $row->{item_key}; } push @{ $results[-1]{action} }, { key => $row->{action_key}, summary => $row->{action_summary}, }; }