示例是在PHP中,但我想在 perl 中创建相同的关联2d数组以及如何打印该数组。 PHP中的EX: -
while($row=mysql_fetch_array($rc))
{
$associative_array[$ClientCode]=array('PartnerCode'=>$row["PartnerCode"],
'OldPartnerCode'=>$row["OldPartnerCode"],
'ClientCode'=>$ClientCode,
'OldClientCode'=> $row["OldClientCode"]);
}
添加OP的评论:
如果2d数组创建正确,那么如何打印该数组。
$sql_sel="select client_id,partner_id,client_code,partner_code from $tblname";
$sth = $dbh->prepare($sql_sel);
$sth->execute();
$nrow=$sth->rows;
while( ($ccode,$pcode,$old_ccode,$old_pcode) = $sth->fetchrow_array) {
$ccode =~ y/A-Z/a-z/;
$pcode =~ y/A-Z/a-z/;
$old_ccode =~ y/A-Z/a-z/;
$old_pcode =~ y/A-Z/a-z/;
$client_partner_hash->{$ccode}={
'newclinetcode'=>$ccode,
'newpartnercode'=>$pcode,
'oldclinetcode'=>$old_ccode,
'oldpartnercode'=>$old_pcode
};
}
答案 0 :(得分:1)
这是您发布的PHP代码的直接翻译。它并非完全不同。 :)
while (my $row = mysql_fetch_array($rc)) {
$associative_array->{$ClientCode} = {
'PartnerCode' => $row->{'PartnerCode'},
'OldPartnerCode' => $row->{'OldPartnerCode'},
'ClientCode' => $ClientCode,
'OldClientCode' => $row->{'OldClientCode'},
};
}
当然请注意,Perl中没有mysql_fetch_array
。相应翻译。 :)
答案 1 :(得分:0)
您可以如下所示获取2D数组中的行数据,并且还给出了如何显示它的数据。
use Data::Dumper
my $associate_array; #Array reference of the @D array
while (my $row = $sth->fetchrow_arrayref()){
$associative_array->[$ClientCode] = {
'PartnerCode' => $row->['PartnerCode'],
'OldPartnerCode' => $row->['OldPartnerCode'],
'ClientCode' => $ClientCode,
'OldClientCode' => $row->['OldClientCode'],
};
}
foreach my $row (@$associative_array){
print Dumper $row;
}
答案 2 :(得分:0)
您可以使用Data :: Dumper,因为有些人建议将哈希对象转储到屏幕上。你可能想做一些更有用的事情。
foreach $ccode(keys(%$client_partner_hash)){
print "C Code: $ccode\n";
print "New Clinet Code: " . $client_partner_hash->{$ccode}->{newclinetcode} ."\n";
print "New Partner Code: " .$client_partner_hash->{$ccode}->{newpartnercode} ."\n";
print "Old Clinet Code: " . $client_partner_hash->{$ccode}->{oldclinetcode} ."\n";
print "Old Partner Code: " .$client_partner_hash->{$ccode}->{oldpartnercode} ."\n";
}
答案 3 :(得分:0)
如果我们将第一个Perl版本重新设想为更多Perl-ish方式,我们可能会得到这样的结果:
use strict;
use warnings;
my $sth = $dbh->prepare(
"select client_id, partner_id, client_code, partner_code from $tblname"
);
$sth->execute();
my %client_partner_hash;
while (my $row = $sth->fetchrow_hashref()) {
$client_partner_hash{lc($$row{client_code})} = +{
map { $_ => lc($$row{$_}) } keys %$row
};
}
如果你想再次提取数据,你可以这么做,比如说:
for my $ccode (sort keys %client_partner_hash) {
my $cp = $client_partner_hash{$ccode};
print 'client_code = ', $$cp{client_code}, "\n";
for my $part (sort keys %$cp} {
if ($part ne 'client_code') {
print " $part = ", $$cp{$part}, "\n";
}
}
}