我正在使用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;
}
$i
和一个总计数$count
,所以肯定可以用if ($i == $counter) { }
来捕获最后一个? - Egg$i > $count
时,$i 的值为0,因此它怎么可能大于 $count 呢? - Eng Cy$reslist
数组结构。 - itzmukeshy7