[英]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,title)创建一个哈希引用
{
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. DBI有许多获取数据的方法。 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. 其中之一称为
fetchall_arrayref()
,它将按照您需要的确切结构将数据返回给您-无需自己构建数据。
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 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. 另外:在声明要
push
循环之外的内容时要小心-在这种情况下应该可以,但是请记住,您要推引用。 If you re-use variables, you can end up with pushing the same reference. 如果您重复使用变量,最终可能会推入相同的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.