$total 的值未在 lumen collection map 函数中设置

Value of $total not being set inside lumen collection map function

我有一个 lumen 集合对象用于我的订单,并使用 map 函数对其进行迭代并执行一些逻辑。我还需要使用 quantity * price 计算的订单总价值。但是负责保存总值的变量总是0.

$total = 0;
$items = Cart_Item::where('user_id', $user->id)->get();
$items = $items->map(function ($item, $key) use ($order, $total) {
    $product = Product::where('id', $item->product_id)->first();
    $order_item = new Order_Item();
    $order_item->order_id = $order->id;
    $order_item->product_id = $item->product_id;
    $order_item->quantity = $item->quantity;
    $order_item->price = $product->GetPrice->price;
    $order_item->save();
    $total = $total + ($order_item->quantity * $order_item->price);
});

无论我做什么,$total总是returns0

您的 closure 的范围不是整个文件的范围,而是仅限于 {} 标签之间的范围。

used 个变量被复制到函数作用域中。

一个解决方案是使 $total 成为一个全局变量:

$total = 0;
$items = Cart_Item::where('user_id', $user->id)->get();
$items = $items->map(function ($item, $key) use ($order, $total) {
    $product = Product::where('id', $item->product_id)->first();
    $order_item = new Order_Item();
    $order_item->order_id = $order->id;
    $order_item->product_id = $item->product_id;
    $order_item->quantity = $item->quantity;
    $order_item->price = $product->GetPrice->price;
    $order_item->save();

    global $total;
    $total = $total + ($order_item->quantity * $order_item->price);
});

另一种方法是将全局作为引用传递 &$total,如下所示:

$total = 0;
$items = Cart_Item::where('user_id', $user->id)->get();
$items = $items->map(function ($item, $key) use ($order, &$total) {
    $product = Product::where('id', $item->product_id)->first();
    $order_item = new Order_Item();
    $order_item->order_id = $order->id;
    $order_item->product_id = $item->product_id;
    $order_item->quantity = $item->quantity;
    $order_item->price = $product->GetPrice->price;
    $order_item->save();

    $total = $total + ($order_item->quantity * $order_item->price);
});