2017-06-26 8 views
-4

重複したコードを避けながら、銀行口座が1つしかない場合、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つの銀行口座は、単純に1つの項目を持つ銀行口座の一覧です。単一のケース== 1つのアイテムのリスト、完全に別個の論理ブランチではない。 – deceze

+0

これをやり直すにはちょっと急進的ではなく、すぐにすぐにこの質問を数分で削除してください。 –

+0

@ this.lau_質問は削除されません。なぜなら、upvoted受け入れられた回答があるからです。 –

答えて

1

銀行口座が1つのみの場合は、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を使用することを検討してください。

+0

単に '$ back_accounts = [BankAccounts :: find_by_id($ id)]'にするのはなぜですか? – deceze

+0

@deceze一般に、私は、コードがより複雑になるにつれて、未定義の変数の問題を避けるために必要な範囲内に変数(例えば、$ bank_accounts)を定義することを好む。この場合、実際にはあなたのメソッドを使用することと同等です。 –

+0

@ this.lau_ありがとうそれは私がもともと述べたようにforeachを持っていた –

関連する問題