如何根据 PHP 中有 2 个计数的数组创建 2 个集合?

How to create 2 collections based from an array with 2 count in PHP?

我知道这是一个基本问题,很抱歉我无法回答,但是如何根据 Laravel/PHP 中具有 2 个值的数组创建 2 个集合?这是我的代码:

 $received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
        foreach($received_items as $received_item) {
            $product_ids = $received_item->product_id;
            foreach($product_ids as $product_item_no => $product_id) {
                $products = Product::where('id', '=', $product_id); 
                $voucher_cost = $products->value('cost');
                $qty_addend = $received_item->qty_per_item;

                $list = array(
                    'product_item_no' => $product_item_no + 1,
                    'product_name' => $products->value('name'),
                    'size' => $products->value('size'),
                    'qty_addend' => $qty_addend[$product_item_no],
                    'voucher_cost' => $voucher_cost,
                    'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
                );

                $list = (object)$list;
                $received_item->list = $list;
                $data = collect([$list]);
            }
        }
        return $data;

基本上,$product_ids 是我想要获取的数组,count($product_ids) 返回 2,但它只是从第二个数组值创建集合。请参阅下面的屏幕截图:

screenshot.png

非常感谢任何帮助。

在你的 $list 变量中它只会存储最后的 product_id 数据,因为你必须将 $list 作为多维数组。 您必须从第二个循环中取出 $list 变量,这样它就不会覆盖数据。

试试下面的代码:

$received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
foreach($received_items as $received_item) {
   $product_ids = $received_item->product_id;
   $list = []; // declare list variable here
   foreach($product_ids as $product_item_no => $product_id) {
       $products = Product::where('id', '=', $product_id);
       $voucher_cost = $products->value('cost');
       $qty_addend = $received_item->qty_per_item;

       $list[] = array( // make it multi-dimentional array
           'product_item_no' => $product_item_no + 1,
           'product_name' => $products->value('name'),
           'size' => $products->value('size'),
           'qty_addend' => $qty_addend[$product_item_no],
           'voucher_cost' => $voucher_cost,
           'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
       );
   }
   // take this code out of loop
   $list = (object)$list;
   $received_item->list = $list;
   $data = collect([$list]);
}
return $data;