1

是否可以使用 php 和 mysql 只运行一个查询,然后执行两个具有不同结果的 while 循环。一世

//this is the query
$qry_offers = mysql_query("SELECT * FROM offers ORDER BY offer_end ASC");

在第一个循环中,我想显示“end_date”小于或等于今天的任何结果

<div id="current">
<?
while($row_offers = mysql_fetch_assoc($qry_offers)) {
    if ( (date("Y-m-d H:i:s")) <= ($row_offers['offer_end']) ) {
        echo '<li><a href="#">'.$row_offers['offer_name'].'</a></li>';
    }
}
?>
</div><!-- END OF CURRENT -->

在第二个循环中,我想显示“end_date”大于今天的任何结果

//this is where i would have the 2n while loop
<div id="inactive">
<?
   while($row_offers = mysql_fetch_assoc($qry_offers)) {
    if ( (date("Y-m-d H:i:s")) > ($row_offers['offer_end']) ) {
        echo '<li><a href="#">'.$row_offers['offer_name'].'</a></li>';
    }
}
?>
</div><!-- END OF INACTIVE -->
4

2 回答 2

5

解决方案是保存每个循环的结果,然后在最后将它们放在一起。

$offers_current = array();
$offers_inactive = array();

while($row_offers = mysql_fetch_assoc($qry_offers)) {
    if ( (date("Y-m-d H:i:s")) <= ($row_offers['offer_end']) )
        $offers_current[] = '<li><a href="#">'.$row_offers['offer_name'].'</a></li>';
    if ( (date("Y-m-d H:i:s")) > ($row_offers['offer_end']) )
        $offers_inactive[] = '<li><a href="#">'.$row_offers['offer_name'].'</a></li>';
}

?>
<div id="current">
    <ul>
    <?php echo implode("\n", $offers_current) ?>
    </ul>
</div>
<div id="inactive">
    <ul>
    <?php echo implode("\n", $offers_inactive) ?>
    </ul>
</div>
于 2012-09-05T02:13:58.417 回答
4

你可以这样做:

$itemsArray = mysql_fetch_assoc($qry_offers);
foreach ( $itemsArray as $row_offers ) {
    // ... Code in here for less than 'offer_end'
}
foreach ( $itemsArray as $row_offers ) {
    // ... Code in here for greater than 'offer_end'
}
于 2012-09-05T02:06:47.730 回答