【问题标题】:Value of $total not being set inside lumen collection map function$total 的值未在流明集合映射函数中设置
【发布时间】:2017-08-13 00:47:18
【问题描述】:

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

【问题讨论】:

    标签: php laravel lumen php-closures


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 2014-02-20
      • 2022-11-01
      • 1970-01-01
      相关资源
      最近更新 更多