开发者

Add a break tag after every record, except the last record?

Is it possible to add a break tag after every record, but not the last record?

Here's my partial code:

if($db->num_rows($query) > 0)
{       
    while($l开发者_JAVA技巧isting = $db->fetch_array($query))
    {
        eval("\$page .= \"".$templates->get("page_template")."\";");
    }
}

Kind regards.


First of all: please don't use eval, there's no benefit to it in this situation and it poses a huge security risk. Second: the theory of "every item but the last" isn't that hard, as you've already got the total number. Something like this may work:

<?php
if($db->num_rows($query) > 0)
{
    $count = 0;
    while($listing = $db->fetch_array($query))
    {
        $page .= $templates->get("page_template");
        if( ++$count !== $db->num_rows( $query ) ) {
            // add break tag.
        }
    }
}

As an alternative (and a cleaner solution), you might want to implode an array of content:

<?php
while( $listing = $db->fetch_array( $query ) ) {
    $pages[] = $templates->get( 'page_template' );
}
$page = implode( 'break-tag', $pages );


A possible solution is to have a counter, lets say $i = 1, and have all rows, lets say $n = $db->num_rows($query).

You print <br /> tags expect in the case where $i == $n Else you print normal and increment $i by one.


maybe not the most graceful.

$row_count = $db->num_rows($query);
$i = 1;
if($row_count > 0)
{       
    while($listing = $db->fetch_array($query))
    {
        if($i == $row_count) { $tag = ""; }else{ $tag = "<br />"; }
// you need to put the $tag below.
    eval("\$page .= \"".$templates->get("page_template")."\";");
        $i++;
    }
}


if you are referring to a <br/> tag...

one way to implement it is to set a boolean for the first loop set to true. At the beginning of the loop, if the boolean is true, don't print anything, if not, print a <br/>. At the end of the first run, set it to false. This way it prints out a <br/> just before the line but not before the first run and it won't print out after the final row.

if($db->num_rows($query) > 0)
{       
    $first_loop = true;    
    while($listing = $db->fetch_array($query))
    {
        if($first_loop !== true)
            echo "<br/>";
        eval("\$page .= \"".$templates->get("page_template")."\";");
        $first_loop = false;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜