2017-06-26 55 views
-4

中的代碼如何在運行foreach循環內的代碼時只使用一個銀行帳戶,同時避免重複的代碼?if語句跳過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> 
+5

不要區分'$ bank_account'和'$ bank_accounts';只有'$ bank_accounts',一個單一的銀行賬戶就是一個銀行賬戶列表,只有一個銀行賬戶。單個案例== 1個項目的列表,不是完全獨立的邏輯分支。 – deceze

+0

是不是有點激進的關閉,現在幾分鐘內即可刪除這個問題,而不用花時間去改進它? –

+0

@ this.lau_這個問題不會被刪除,因爲有一個upvoted被接受的答案 –

回答

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> 

還要考慮使用foreach/endforeach HTML代碼中,因爲它是更具可讀性。

+0

爲什麼不簡單地'$ back_accounts = [BankAccounts :: find_by_id($ id)]'? – deceze

+0

@deceze,通常我更喜歡在需要的範圍內定義變量(例如。$ bank_accounts),以避免未定義的變量問題,因爲代碼變得更復雜。在這種情況下,它確實相當於使用你的方法。 –

+0

@ this.lau_感謝它的工作,我原來有foreach,正如你所提到的 –