1

我的订单有一个流明集合对象,并使用 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总是返回0

4

1 回答 1

2

闭包的范围不是整个文件的范围,但仅限于{}标签之间的内容。

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);
});
于 2017-03-21T11:30:53.060 回答