简体   繁体   中英

Find last row in a foreach query

How could I find the last post and NOT put <hr> below it?

<?php foreach($db->query("SELECT * FROM news") as $row): ?>
<div class="NewsHeadline">
<div class="NewsDate"><?php echo $date; ?> - </div>
<div class="NewsTitle"><?php echo $title; ?></div>
</div>

<div class="NewsBody">
<?php echo $body; ?>
</div>

<hr>
<?php endforeach ?>

Set a counter equal to 1 which increments each round, and check if it is equal to the count() of the $query array returned. If it is, you are on the last round!

<?php 
    $counter = 1; 
    $total = count($db->query("SELECT * FROM news"));
?>
<?php foreach($db->query("SELECT * FROM news") as $row): ?>
    <div class="NewsHeadline">
        <div class="NewsDate"><?php echo $date; ?> - </div>
        <div class="NewsTitle"><?php echo $title; ?></div>
    </div>

    <div class="NewsBody">
        <?php echo $body; ?>
    </div>
    <?php if($counter != $total){
    ?>
        <hr>
    <?php
    }

   ?>

<?php $counter++; ?>
<?php endforeach ?>

A solution would be to build an array and then use join :

<?php
$arr=array();
foreach($db->query("SELECT * FROM news") as $row):
    $arr[] = '<div class="NewsHeadline"><div class="NewsDate">'.$date
        .' - </div><div class="NewsTitle">'.$title'
        .</div></div><div class="NewsBody">'.$body.'</div>';
endforeach
echo join("<hr>",$arr);    
?>

You can convert to regular for loop and then compare $i to the size of your query result:

<?php 
    $news = $db->query("SELECT * FROM news");

    for($i=0; $i<sizeof($news);$i++){ ?>
        <div class="NewsHeadline">
            <div class="NewsDate"><?php echo $date; ?> - </div>
            <div class="NewsTitle"><?php echo $title; ?></div>
        </div>

        <div class="NewsBody">
            <?php echo $body; ?>
        </div>

        <?php if(($i+1) < sizeof($news)) echo '<hr>'; ?> 
<?php } ?>

If you get a count of the rows prior to the loop, you can check the count and avoid adding the HR.

$rows = $db->query("SELECT * FROM news");
$row_count = $rows.count();
$iter = 0;
foreach($rows as $row) 
{
   //...
   if ($iter < $row_count)
   {
        // render hr
   }
   $iter++;
 }

You could also go with a pure CSS approach:

div.containerClass:last-child hr { display:none; }

where "containerClass" would be whatever element your posted code sits inside of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM