Php或JavaScript中的Foreach循环解决方案

fkaflof6  于 12个月前  发布在  PHP
关注(0)|答案(1)|浏览(117)

我想创建一个foreach循环,在每个循环中将值A与不同的值(Value(n))进行比较,如果值A大于value(n),则循环应继续,直到循环中的项目完成。
但问题是,我希望每次交互时,A的值都要减去与之比较的值(n)。因此,在下一次迭代中,Value A小于上一次循环中的值,即A的新值= value A - Value(n)。

public function create(Request $data, User $user): Payment
{
    return DB::transaction(function () use($data, $user) {
        $payment = $user->payments->create([
            'amount_paid'   => $data->amount,
            'pay_method'    => $data->payMethod,
            'comment'       => $data->comment,
            'patient_id'    => $data->patientId,
            'visit_id'      => $data->visitId,
        ]);

        $totalPayments = $payment->visitPayments($payment->visit);

        $payment->visit->update([
            'total_paid' => $totalPayments
        ]);

        $totalPaymentsforPrescriptions = $totalPayments;

        $prescriptions = $payment->visit->prescriptions;

        foreach($prescriptions as $prescription) {
            &$totalPaymentsforPrescriptions = $totalPaymentsforPrescriptions - $prescription->hmo_bill;
            
        }
        return $payment;
    });
}

字符串
不知道如何将A的新值返回到正在进行的foreach循环。
我试图通过引用与号(&)来改变循环外的变量,但我得到了一个错误(红色下划线),这是意外的。
我看起来还不明白。我想是缺乏知识。

wljmcqd8

wljmcqd81#

在PHP中,在foreach循环中使用引用(&)通常是对循环变量本身进行的,而不是对循环外部的变量进行的。

public function create(Request $data, User $user): Payment
{
    return DB::transaction(function () use ($data, $user) {
        $payment = $user->payments->create([
            'amount_paid'   => $data->amount,
            'pay_method'    => $data->payMethod,
            'comment'       => $data->comment,
            'patient_id'    => $data->patientId,
            'visit_id'      => $data->visitId,
        ]);

        $totalPayments = $payment->visitPayments($payment->visit);

        $payment->visit->update([
            'total_paid' => $totalPayments
        ]);

        $totalPaymentsforPrescriptions = $totalPayments;

        $prescriptions = $payment->visit->prescriptions;

        foreach ($prescriptions as $prescription) {
            if ($totalPaymentsforPrescriptions > $prescription->hmo_bill) {
                $totalPaymentsforPrescriptions -= $prescription->hmo_bill;
            }
        }

        return $payment;
    });
}

字符串

相关问题