【问题标题】:Getting Array Data throught Loop on Laravel 8在 Laravel 8 中通过循环获取数组数据
【发布时间】:2021-10-31 20:34:26
【问题描述】:

我正在使用一种将数组数据发送到控制器的表单。它还接收到这样的数组数据

$product_unit = $inputs['orderProducts'];

但问题是当我通过 foreach 循环传递这些数据以匹配其他产品时,它只显示一个数组。

foreach ($product_unit as $unit){
        $product = Product::all()
            ->where('id', '=', $unit['product_id'])
            ->where('unit', '>=', $unit['quantity'])
            ->first();
    }

在这里,我想将接收到的数组数据与插入的现有产品相匹配。如果它匹配现有数据,它将增加。但在这里它只能传递单个数组。这就是为什么它只是增加一行值。特别是最后匹配的值会增加。那么如何通过laravel中的where函数循环该数组数据。

【问题讨论】:

  • 每次迭代都会覆盖$product

标签: php arrays laravel foreach get


【解决方案1】:

你必须像下面这样使用。

$product= array();

foreach ($product_unit as $unit){
    $product[] = Product::all()
        ->where('id', '=', $unit['product_id'])
        ->where('unit', '>=', $unit['quantity'])
        ->first();
}

dd($product)

【讨论】:

  • 为什么,你不向 OP 描述出了什么问题
  • @Daan,已经描述过了。但我也必须描述。这是我的错
【解决方案2】:

$product 变量应该是一个数组;

$product[]

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 2016-03-23
    • 2018-08-10
    • 2019-10-31
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    相关资源
    最近更新 更多