首页  >  问答  >  正文

将空函数与 Foreach 循环结合使用

我想在数据库中没有项目时输出一条消息。这 当数据库没有数据时,代码不会打印语句。

This is my code,
<?php foreach($latest_tenders as $tenders):
if(!empty($tenders)){ 
$time = strtotime($tenders['post_date']);
                      $month=date('m', $time);
                                switch($month){
                                   case 1:
                                    echo "January "; break;
                                      .
                                      .
                                      .
                                    case 12:
                                     echo "December "; break;
                                   default:
                                    echo "January ";
                            }
echo date('d', $time).', ';
echo date('Y', $time).'&nbsp';
echo date('h', $time).':'; echo date('i',     $time).' |&nbsp';?>
     <i class="fas fa-user"></i> <?php echo $tenders['author'];?></p> 
       </div><br/>
     <?php 
         }
            else{?>
      <p style=" font-size:13px; word-spacing: 5px;color:tomato;">
          Tender Name: No advertised Tenders, Check again later.
      </p>
        <?php
            }
            endforeach;
            ?>

P粉988025835P粉988025835429 天前496

全部回复(1)我来回复

  • P粉283559033

    P粉2835590332023-09-08 00:14:25

    假设$latest_tenders是您的数据库结果,首先检查$latest_tenders数组是否不为空。如果不为空:循环遍历 $latest_tenders 并打印其 $tenders。否则(为空):打印您的错误消息。

    <?php if(!empty($latest_tenders)) : ?>
        <?php foreach($latest_tenders as $tenders):
            $time = strtotime($tenders['post_date']);
            $month=date('m', $time);
            switch($month){
                case 1:
                    echo "January "; break;
                        .
                        .
                        .
                default:
                    echo "January ";
            }
            echo date('d', $time).', ';
            echo date('Y', $time).'&nbsp';
            echo date('h', $time).':';
            echo date('i',     $time).' |&nbsp';
        ?>
            <i class="fas fa-user"></i> <?php echo $tenders['author'];?></p></div><br/>
        <?php endforeach; ?>
    <?php else : ?>
        <p style=" font-size:13px; word-spacing: 5px;color:tomato;">
            Tender Name : No advertised Tenders for No, Check again later.
        </p>
    <?php endif; ?>

    回复
    0
  • 取消回复