简体   繁体   中英

push hash ref into array ref perl

i am fetching data from a database...what i would like to achieve is for every data row fetched(id,title) to create a hash ref

{
   id => data->[0],
   title => data[1]
}

and push this hash ref into array ref in order to create the following format

 {  category => [
                   {
                    id => 1,
                    title => "title1"
                   },
                   {
                   id => 2,
                   title => "title2"
                   }
                  ]
              }

what i have made:

   my $productCategories->{category} = [];
    my $product = {};
    my $sth = $dbh->prepare(qq[SELECT id,title FROM ].DB_SCHEMA().qq[.product_categories]) || die $dbh->errstr;
    $sth->execute() || die $dbh->errstr;
    while(my $data = $sth->fetch){
        $product =  {
                    id      =>  $data->[0],
                    title   =>  $data->[1]
                    };
        push $productCategories->{category}, $product;
    }

but it is not working...

DBI has many methods for fetching data. One of them is called fetchall_arrayref() and it will give you back the data in exactly the structure that you need - no need to build it up yourself.

my $sth = $dbh->prepare(qq[SELECT id,title FROM ] .
                        DB_SCHEMA() .
                        qq[.product_categories])
  || die $dbh->errstr;

$sth->execute() || die $dbh->errstr;

# Pass a hash ref to get each row back as a hash.
$productCategories->{category} = $sth->fetchall_arrayref({});

Turn on use strict; use warnings; and it'll tell you why.

push on reference is experimental

Not an ARRAY reference

Try:

push @{$productCategories->{category}}, $product;

Also: Be careful with declaring things you're push ing outside the loop - you should be ok in this case, but bear in mind you're pushing a reference. If you re-use variables, you can end up with pushing the same reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM