将Perl数组中的项放入for循环以打印出HTML

时间:2016-05-04 23:20:26

标签: html arrays json perl for-loop

我使用Perl将密钥从JSON数据拉入变量以在数组中使用。我想在HTML表格中打印出这些变量。

我有变量工作,但我不知道如何让它们连续打印,直到不再有。

这是我的Perl代码。下面是我的HTML,其中包含HTML表格,其中我打印了数组中的数据。但我必须在表格中键入每个变量才能打印。

我想要它所以它会自动添加新行,直到没有更多数据。

这是.pl文件的顶部,它是Perl部分

#!/usr/bin/perl -w

use CGI qw/:standard/;
use strict;
use warnings;
use JSON qw( decode_json );
use LWP::Simple 'get'; 
use Data::Dumper; 

print "content-type:text/html; charset=utf-8\n\n";

my @sessionArr;
my @classArr;
my @timeArr;
my @adminArr;
my @profArr;
my @descArr;

my $i = 0;

my $myURL = "Leaving URL out for obvious reasons";

my $json = get($myURL);
die "Could not get $myURL!" unless defined $json;

my $decoded_json = decode_json ($json);

my @sessionID = @{ $decoded_json->{'items'} };
foreach my $d ( @sessionID ) {
 $sessionArr[$i] = $d->{"sessionID"};
 $i = $i + 1;
}

$i = 0;

my @class = @{ $decoded_json->{'items'} };
foreach my $d ( @class ) {
 $classArr[$i] = $d->{"classField"};
 $i = $i + 1;
}

$i = 0;


my @time = @{ $decoded_json->{'items'} };
foreach my $d ( @time ) {
  $timeArr[$i] = $d->{"startTimeField"};
  $i = $i + 1;
}

$i = 0;

my @usrcreater = @{ $decoded_json->{'items'} };
foreach my $d ( @usrcreater ) {
  $adminArr[$i] = $d->{"leader"};
  $i = $i + 1;
}

$i = 0;

my @professor = @{ $decoded_json->{'items'} };
foreach my $d ( @professor ) {
  $profArr[$i] = $d->{"professorField"};
  $i = $i + 1;
}

$i = 0;




my @description = @{ $decoded_json->{'items'} };
foreach my $d ( @description ) {
  $descArr[$i] = $d->{"descriptionField"};
  $i = $i + 1;
}

$i = 0;

foreach my $p ( @description ) {
   $i = $i +1;
}

现在这里是HTML格式

<h1>View Study Sessions</h1>

<table border="1" align="center">
<tr>
<th>Session ID</th>
<th>Course Name</th>
<th>Start Time</th>
<th>Administrator</th>
<th>Instructor</th>
<th>Description</th>
</tr>

<tr>
<td>$sessionArr[0]</td>
<td>$classArr[0]</td>
<td>$timeArr[0]</td>
<td>$adminArr[0]</td>
<td>$profArr[0]</td>
<td>$descArr[0]</td>
</tr>

<tr>
<td>$sessionArr[1]</td>
<td>$classArr[1]</td>
<td>$timeArr[1]</td>
<td>$adminArr[1]</td>
<td>$profArr[1]</td>
<td>$descArr[1]</td>
</tr>

<tr>
<td>$sessionArr[2]</td>
<td>$classArr[2]</td>
<td>$timeArr[2]</td>
<td>$adminArr[2]</td>
<td>$profArr[2]</td>
<td>$descArr[2]</td>
</tr>

<tr>
<td>$sessionArr[3]</td>
<td>$classArr[3]</td>
<td>$timeArr[3]</td>
<td>$adminArr[3]</td>
<td>$profArr[3]</td>
<td>$descArr[3]</td>
</tr></table> 

<br>
<br>

这是我正在看的内容的屏幕截图。如您所见,输出位于图像的顶部。我希望它在页面中更低

3 个答案:

答案 0 :(得分:2)

我认为您的$decoded_json->{items}包含一系列哈希(对象),其中包含属性sessionIDclassField,....

如果是这种情况,您可以迭代该数组并打印属性(哈希元素),如下所示:

print "<tr>\n";
foreach my $item ( @{ $decoded_json->{'items'} } ) {
    printf( "<td>%s</td>\n", $item->{sessionID} );
    printf( "<td>%s</td>\n", $item->{classField} );
    printf( "<td>%s</td>\n", $item->{startTimeField} );
    printf( "<td>%s</td>\n", $item->{leader} );
    printf( "<td>%s</td>\n", $item->{professorField} );
    printf( "<td>%s</td>\n", $item->{descriptionField} );
}
print "</tr>\n";

答案 1 :(得分:1)

这是一个重写,使用Template Toolkit(&#34; TT&#34;)来构建HTML页面并包含来自JSON的数据

原始HTML存在许多问题。标签是不平衡的,并且您在体内只有头部元素。我无法保证这可以解决所有问题,但我无法发现任何错误。您应该小心保持HTML缩进,以便您可以更轻松地发现不平衡的标记。它还避免了对结束标记进行评论的必要性

我已经包含了一段代码,向您展示如何更轻松地从每个哈希列表中提取相同字段的数组。变量未被使用,因此,一旦您理解了课程,请删除该代码

Template Toolkit的模板通常保存在单独的.tt文件中。在这种情况下,我使用了DATA文件句柄,因为它更符合您编写原始代码的方式。但请记住,TT模板可能包含引用其他单独文件的include语句。例如,您可以将页脚部分放在外部文件中,然后在主模板中放置[% INCLUDE footer.tt %]。但这是为了未来

请注意,Template Toolkit允许您直接访问Perl数据结构。模板需要使用的任何内容都必须在process方法调用的第二个参数中传递。在这种情况下,我已通过{ json => $decoded_json },以便TT现在可以使用json标识符来引用您已下载的哈希值。在模板中,json.items现在是数据数组(可以json.items.0json.items.1等方式访问),在这里我写了[% FOREACH item IN json.items %]来声明一个新的TT变量{{ 1}}并依次将它分配给item数组的每个元素

我希望所有这一切都很清楚

items

输出

#!/usr/bin/perl

use utf8;
use strict;
use warnings qw/ all FATAL /;

use CGI qw/:standard/;
use JSON qw( decode_json );
use LWP;
use Template;

use Data::Dumper; 

use constant JSON_URL => 'http://example.com/json';

### This code uses a literal JSON data item. The live code should
### fetch the real data from the JSON_URL. The code to do this
### is here but has been commented out

=comment
my $json = do {
    my $ua = LWP::UserAgent->new;
    my $resp = $ua->get(JSON_URL);
    unless ( $resp->is_success ) {
        die sprintf "Could not retrieve JSON data: %s", $resp->status_line;
    }
    $resp->decoded_content;
};
=cut

my $json = <<END;
{
    "items": [
        {
            "sessionID":        "session1",
            "classField":       "class1",
            "startTimeField":   "start1",
            "leader":           "leader1",
            "professorField":   "prof1",
            "descriptionField": "desc1"
        },
        {
            "sessionID":        "session2",
            "classField":       "class2",
            "startTimeField":   "start2",
            "leader":           "leader2",
            "professorField":   "prof2",
            "descriptionField": "desc2"
        }
    ]
}
END

my $decoded_json = decode_json($json);


### Note that these variables are unused. This is just an example
### of a better way to extract a list of fields from an array
### Please remove this code before deploying

my $items = $decoded_json->{items};

my @sessionArr = map { $_->{sessionID} } @$items;
my @classArr   = map { $_->{classField} } @$items;
my @timeArr    = map { $_->{startTimeField} } @$items;
my @adminArr   = map { $_->{leader} } @$items;
my @profArr    = map { $_->{professorField} } @$items;
my @descArr    = map { $_->{descriptionField} } @$items;

### All that needs to be done its to use CGI to print the HTTP
### header and invoke Template Toolkit to build an HTML page that
### includes the data from the JSON hash

print CGI->header(
    -type    => 'text/html',
    -charset => 'utf-8',
);

my $tt = Template->new;

$tt->process(\*DATA, { json => $decoded_json } );

__DATA__
<!DOCTYPE html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <title>AU Study Sessions</title>

    <link href="../css/bootstrap.css" rel="stylesheet">

    <link href="../css/main.css" rel="stylesheet">

    <!--[if lt IE 9]>
      <script src="js/html5shiv.js"></script>
      <script src="js/respond.min.js"></script>
    <![endif]-->

    <link rel="shortcut icon" href="../images/favicon.png">
    <script src="../js/pace.js"></script>

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,600' rel='stylesheet' type='text/css'>

</head>

<body>

    <div class="preloader"></div>

    <!-- ******************** MASTHEAD SECTION ******************* -->

    <main id="top" class="masthead" role="main">
        <div class="container">
            <div class="logo">
                <a href=""><img src="../images/aulogo2.png" alt="logo"></a>
            </div>

            <h1>View Study Sessions</h1>);

            <table>

            [% FOREACH item IN json.items %]
            <tr>
                <td>[% item.sessionID %]</td>
                <td>[% item.classField %]</td>
                <td>[% item.startTimeField %]</td>
                <td>[% item.leader %]</td>
                <td>[% item.professorField %]</td>
                <td>[% item.descriptionField %]</td>
            </tr>
            [% END %]

            <br/>
            <br/>

            <a href=""> Add a Study Session</a>

            <!--
            <a href="index.html#explore" class="scrollto">
                <p>SCROLL DOWN TO EXPLORE</p>
                <p class="scrollto--arrow"><img src="../images/scroll_down.png" alt="scroll down arrow"></p>
            </a>
            -->

        </div> <!-- class="container" -->
    </main>

    <!-- ******************** FOOTER SECTION ******************** -->  

    <div class="container" id="explore">

        <div class="section-title">
            <h2>With Adelphi Study Sessions Website</h2>
            <h4>You will be able to do the following</h4>
        </div>

        <section class="row features">

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_01.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>View Study Groups</h3>
                        <p>See the most up to date study sessions taking place on our garden city campus.</p>
                    </div>
                </div>
            </div>

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_02.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>Add and create new study sessions</h3>
                        <p>If you or some classmates want to create a new study session you will be able to add a new group along with course information, sudy topics, and time and location taking place.</p>
                    </div>
                </div>
            </div>

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_03.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>See description of session</h3>
                        <p>The student who creates the study session will give a short description about what the study session will cover.</p>
                    </div>
                </div>
            </div>

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_04.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>Available on campus</h3>
                        <p>All study sessions will take place on our Garden City campus therefore are available to all students who commute or live on campus.</p>
                    </div>
                </div>
            </div>

        </section>

        <script src="../js/jquery.js"></script>
        <script src="../js/bootstrap.js"></script>
        <script src="../js/easing.js"></script>
        <script src="../js/nicescroll.js"></script>

    </div> <!-- class="container" id="explore" -->

</body>

</html>

答案 2 :(得分:0)

您需要为表格生成HTML。表的每个“列”的数据都在其自己的数组中。因此,一行中的每个单元格都来自同一索引处的单独数组。第1行由来自数组的数据产生,每个数组在索引0处,第2行由每个数组的索引1等产生。因此,您需要在行中打印与数组一样多的单元格,并且需要尽可能多的行数组中的元素。

这是一种方法。引用您的数组并将它们存储在另一个数组@rcols中。然后循环遍历任何一个数组的索引,并打印出该行的所有单元格(<td>元素)。单元格的数据来自该索引的数组,通过循环@rcols

my @rcols = (\@sessionArr, \@classArr, \@timeArr,         
    \@adminArr, \@profArr, \@descArr);

foreach my $i (0..$#sessionArr) {
    print "<tr>\n";
    foreach my $ra (@rcols) {
        print "<td>$ra->[$i]</td>\n"
    }
    print "</tr>\n";
}

这将生成表格的所有数据(包含所有单元格的行)。