$y = 0; @loop = (); while($y < $x) { my %items; $items{_TOPIC} = $topic[$y]; $sth = $dbh->prepare("SELECT item1, item2, item3 FROM table WHERE topic='$topic[$y]' ORDER BY id ASC"); $sth->execute(); @subloop = (); while(@ary = $sth->fetchrow_array()) { my %subitems; $subitems{_first_item} = $ary[0]; $subitems{_second_item} = $ary[1]; $subitems{_third_item} = $ary[2]; push(@subloop, \%subitems); } $items{_ITEMS} = \@subloop; push(@loop, \%items); $y++; } $html->param(_TOPICS => \@loop); $html->output;