2016-03-23 4 views
3

私はforeachをループしています。このようなロジックを作る必要があります: 反復が最後でない場合。価格を集める。反復が最後のときです。集められた価格で合計から減算する。最後の反復価格を除きます。私は次のコードを持っていない。しかし、それは動作していません。最後の反復を除いてforeachループで何かを決定して行います。

$i = 0; 
    $credit = ''; 
    $count = count($reslist); 

    foreach ($reslist as $single_reservation) { 
      //All of the transactions to be settled by course 
      //$credit    = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value'); 

      if ($i > $count && $single_reservation != end($reslist)) { 
       $gather_sum_in_czk += $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value'); 
       $credit    = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value'); 
      } 
      //Last iteration need to subtract gathered up sum with total. 
      else { 
       $credit = $suminczk - $gather_sum_in_czk; 
      } 
    $i++; 
    } 

EDIT:すべての対話EXECPT LASTの価格を集めしようとしている:

  if ($i != $count - 1 || $i !== $count - 1) { 
       $gather_sum_in_czk += $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value'); 
       $credit    = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value'); 
      } 

      else { 
       $credit = $suminczk - $gather_sum_in_czk; 
      } 
+2

あなたは '$ i'と' $ count'に総数を持っていますので、 'if($ i == $ counter){}'は最後のものを捕まえますか? – Egg

+0

最初のループの '$ i> $ count'では、$ iは0です。したがって、$ countよりもどのように大きいでしょうか? –

+0

私の編集を参照してください。私は最初にすべてのexecptを集める必要があります。 '$ reslist'には最後の – Prague2

答えて

1

SPL CachingIteratorは常に、その内側iteratorの背後にある一つの要素である。それ故、それはを経由して次の要素を生成するかどうかを報告することができます。
この例では、generatorを選択しています。これは、このアプローチが追加データに依存していないことを実証しています。 count($ array)。

<?php 
// see http://docs.php.net/CachingIterator 
//$cacheit = new CachingIterator(new ArrayIterator(range(1,10))); 
$cacheit = new CachingIterator(gen_data()); 

$sum = 0;     
foreach($cacheit as $v) { 
    if($cacheit->hasNext()) { 
     $sum+= $v; 
    } 
    else { 
     // ...and another operation for the last iteration 
     $sum-=$v; 
    } 
} 

echo $sum; // 1+2+3+4+5+6+7+8+9-10 = 35 


// see http://docs.php.net/generators 
function gen_data() { 
    foreach(range(1,10) as $v) { 
     yield $v; 
    } 
} 
0

foreach PHPの配列を-ingキー(整数インデックス純粋アレイ場合)と値の両方を返します。次の構文を使用して、値を使用できるようにするには:

その後、
foreach ($array as $key => $value) { 
... 
} 

あなたは$key >= count($array) - 1(0ベースの配列に覚えているかどうかを確認することができ、最後の要素はcount($array) - 1ある

あなたの元のコードはほとんど作品。 、ただ間違ったif状態で。代わりに$i > $count$i >= $count - 1を使用してください。

+0

キーを使用するのは、配列キーに数値のインデックス値を使用する場合のみです。プラハ2は配列の作成方法や実装方法を示していないので、これは少し前提です。 '$ i'カウンタを使う方がより信頼できます。 –

+0

キーと値を格納している配列は数値ではない – Prague2

+0

実際にはキーの前提です。ただし、最後の段落が適用されます。 – LeleDumbo

関連する問題