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

3
我正在使用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++;
    }

编辑:尝试收集除最后一个之外的所有交互的价格:

          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
在第一次循环中,当 $i > $count 时,$i 的值为0,因此它怎么可能大于 $count 呢? - Eng Cy
请看我的编辑。我需要先收集除最后一个之外的所有内容,然后使用最后一个。 - Prague2
共享 $reslist 数组结构。 - itzmukeshy7
如果您知道循环将运行的次数,则将该数字保存为变量并在每个相应的迭代中检查其值。 - Gunaseelan
2个回答

1

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

0
在PHP中使用foreach循环遍历数组会返回键值对(如果是纯数组,则键是整数索引)。要只获取值,请使用以下代码结构:
foreach ($array as $key => $value) {
...
}

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

您原来的代码几乎可以工作,只是在 if 条件中有误。请使用 $i >= $count - 1 而不是 $i > $count


仅当您对数组键使用数字索引值时,使用键才有效。由于@Prague2没有展示如何创建或填充数组,因此这有点冒险。使用“$i”计数器更为可靠。 - Geoff Atkins
我的数组只存储键和值,而不是数字。 - Prague2
确实,这是对键的一种假设。然而,最后一段适用。 - LeleDumbo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接