if语句跳过foreach但仍在

时间:2017-06-26 14:29:53

标签: php

当我只有一个银行帐户时,如何在foreach循环内运行代码,同时避免重复代码?

<?php 
    if($_GET['bank_id']>0){
        $id = ($_GET['bank_id']);
        $bank_account = BankAccounts::find_by_id($id); 
    }else{
        $bank_accounts = BankAccounts::find_all(); 
    }
?>

    <table class="bordered">
      <tr>
        <th>accounts id</th>    
        <th>accounts name</th>  
        <th>accounts number</th>    
        <th>account</th>    
      </tr>

    <?php 
    if(isset($bank_accounts)){
    foreach($bank_accounts as $bank_account){
        ?>
      <tr>
        <th><?php echo $bank_account -> bank_accounts_id; ?> </th>  
        <th><?php echo $bank_account -> bank_accounts_name; ?> </th>    
        <th><?php echo $bank_account -> bank_accounts_number; ?> </th>  
        <th><?php echo $bank_account -> bank_account; ?> </th>  
      </tr>
    <?php
        } 
        }else{
    ?>
        <tr>
        <th><?php echo $bank_account -> bank_accounts_id; ?> </th>  
        <th><?php echo $bank_account -> bank_accounts_name; ?> </th>    
        <th><?php echo $bank_account -> bank_accounts_number; ?> </th>  
        <th><?php echo $bank_account -> bank_account; ?> </th>  
      </tr>
 <?php  } ?>
    </table>

1 个答案:

答案 0 :(得分:1)

如果您只有一个银行帐户,请将其添加到包含一个元素的数组中。这样可以避免重复代码,意味着统一处理0,1或多个银行账户:

<?php 
  $bank_accounts = array();
  if($_GET['bank_id']>0){
    $id = ($_GET['bank_id']);
    $bank_account = BankAccounts::find_by_id($id); 
    $bank_accounts[] = $bank_account;
  } else {
    $bank_accounts = BankAccounts::find_all(); 
  }
?>

<table class="bordered">
  <tr>
    <th>accounts id</th>    
    <th>accounts name</th>  
    <th>accounts number</th>    
    <th>account</th>    
  </tr>

  <?php foreach($bank_accounts as $bank_account): ?>
    <tr>
      <th><?php echo $bank_account -> bank_accounts_id; ?> </th>  
      <th><?php echo $bank_account -> bank_accounts_name; ?> </th>    
      <th><?php echo $bank_account -> bank_accounts_number; ?> </th>  
      <th><?php echo $bank_account -> bank_account; ?> </th>  
    </tr>
  <?php endforeach; ?>
</table>

另请考虑在HTML代码中使用foreach/endforeach,因为它更具可读性。