将表格单元格与标题相关联

时间:2009-10-29 02:17:06

标签: sql perl header

我想将表格中的单元格值与其标题相关联。标题是未知的,因为它是 由SQL查询生成。

标题大小来自SQL返回结果。然后把它放到一个数组中,

@sizes = qw(S36 S37 S38 S39 S40 S41 S42);

现在,如果詹姆斯的身高是S38。

我想将它们打印为带有尺寸标题的HTML表格:

+--------+--------+--------+-------+-------+-------+-------+
|    S36 |    S37 |    S38 |   S39 |   S40 |   S41 |   S42 |
+--------+--------+--------+-------+-------+-------+-------+
|        |        |  James |       |       |       |       |
+--------+--------+--------+-------+-------+-------+-------+

我知道如果大小是行或结果的一部分,但是作为表头?

,如何执行此操作

如何用Perl操纵它?

编辑:

我试着总结一下我试过的代码......

SQL查询:

select size from articles where order_number = "3";

进入阵列:

while(my $ref = $sth->fetchrow_hashref()) {
    $size = "$ref->{'size'}";
    push @sizes, $size;
}

说,@sizes是:

@sizes = qw(S36 S37 S38 S39 S40 S41 S42);

根据尺寸创建HTML标头:

+--------+--------+--------+-------+-------+-------+-------+
|    S36 |    S37 |    S38 |   S39 |   S40 |   S41 |   S42 |
+--------+--------+--------+-------+-------+-------+-------+

现在,从另一个SQL查询说,我知道詹姆斯有S38。 如何放入上表的右侧行单元格。它将是:

+--------+--------+--------+-------+-------+-------+-------+
|    S36 |    S37 |    S38 |   S39 |   S40 |   S41 |   S42 |
+--------+--------+--------+-------+-------+-------+-------+
|        |        |  James |       |       |       |       |
+--------+--------+--------+-------+-------+-------+-------+

1 个答案:

答案 0 :(得分:2)

以下是使用CGI.pm HTML生成方法执行此操作的方法:

#!/usr/bin/perl

use strict;
use warnings;

use CGI qw(:html);
use List::AllUtils qw( first_index );

my @sizes = qw(S36 S37 S38 S39 S40 S41 S42);
my %person = ( name => 'James', size => 'S38');

my @row = ('') x @sizes;
$row[ first_index { $_ eq $person{size} } @sizes ] = $person{name};

print start_html,
      table( { border => 1 },
          Tr(td({width => sprintf('%.0f%%', 100/@sizes)}, \@sizes)),
          Tr(td(\@row) ) ),
      end_html;

另一方面,我很喜欢HTML::Template

#!/usr/bin/perl

use strict; use warnings;

use HTML::Template;
use List::AllUtils qw( first_index );

my @sizes = qw(S36 S37 S38 S39 S40 S41 S42);
my %person = ( name => 'James', size => 'S38');

my @row = (' ') x @sizes;
$row[ first_index { $_ eq $person{size} } @sizes ] = $person{name};

my $tmpl_txt = <<EO_TMPL;
<html><head><style type="text/css">
#size_chart { margin: 0 auto; }
#size_chart td { width: <TMPL_VAR CELL_WIDTH>; border: 2px inset #ddd }
</style></head>
<body><table id="size_chart">
<TMPL_LOOP ROWS><tr>
<TMPL_LOOP CELLS><td><TMPL_VAR CELL></td></TMPL_LOOP>
</tr></TMPL_LOOP>
</table></body></html>
EO_TMPL

my $tmpl = HTML::Template->new(scalarref => \$tmpl_txt);
$tmpl->param(
    CELL_WIDTH => sprintf('%.0f%%', 100/@sizes),
    ROWS => [ { CELLS => [ map { { CELL => $_ } } @sizes ] },
              { CELLS => [ map { { CELL => $_ } } @row ]   },
]);

print $tmpl->output;