在foreach循环中确定并执行除最后一次迭代之外的操作


Determine and do stuff in foreach loop except the last iteration

我正在循环一个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++;
    }

编辑:试图收集所有交互的价格EXECPT最后:

          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;
            }

SPL CachingIterator始终是其内部迭代器后面的一个元素。因此,它可以通过->hasNext()
在这个例子中,我选择了一个生成器来证明这种方法不依赖于任何额外的数据,比如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;
    }
}

foreach在PHP中处理数组时同时返回键(如果是纯数组,则为整数索引)和值。为了能够使用该值,请使用以下构造:

foreach ($array as $key => $value) {
...
}

然后可以检查$key >= count($array) - 1(记住,在基于0的数组中,最后一个元素是count($array) - 1

您的原始代码几乎可以工作,只是在if条件下出错。使用$i >= $count - 1而不是$i > $count