in reply to Grouping an array of hashrefs by similar key values
@items = ( { item_key => '1', item_description => 'description 1', item_summary => 'item summary 1', actions => [ { key => '1', summary => 'summary 1' }, { key => '2', summary => 'summary 2' } ] }, ... );
You could do multiple queries.
my $items_sth = $dbh->prepare('SELECT * FROM Items'); my $actions_sth = $dbh->prepare('SELECT * FROM Actions WHERE item_key += ?'); my @items; $items_sth->execute($item_row->{item_key}); while (my $item_row = $items_sth->fetch_hashref()) { my $item = { item_key => $item_row->{item_key}, item_description => $item_row->{item_description}, item_summary => $item_row->{item_summary}, actions => [], }; my $actions = $item->{actions}; $actions_sth->execute($item_row->{item_key}); while (my $action_row = $actions_sth->fetch_hashref()) { push @$actions, { key => $action_row->{action_key}, summary => $action_row->{action_summary}, }; } push @items, $item; }
You could order your query results by item_key and look at the last record key processed
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}, }; }
You could use a lookup table
my %items; my @items; while ($row = $sth->fetch_hashref()) { our $item; local *item = \( $items{ $row->{item_key} } ); if (!$item) { $item = { item_key => $row->{item_key}, item_description => $row->{item_description}, item_summary => $row->{item_summary}, actions => [], }; push @items, $item; } push @{ $item->{action} }, { key => $row->{action_key}, summary => $row->{action_summary}, }; }
This method requires more memory. Use the second method if ordering by item_key is acceptable.
You could technically use the last two techniques to build the data structure you desire from the data structure you presented, if you can't build the data structure you desire directly from the database (as shown).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Grouping an array of hashrefs by similar key values
by perldj (Initiate) on Jan 29, 2009 at 19:24 UTC | |
by ikegami (Patriarch) on Jan 29, 2009 at 19:35 UTC |