如何在 PHP 中从具有 2 个计数的数组创建 2 个集合?
Posted
技术标签:
【中文标题】如何在 PHP 中从具有 2 个计数的数组创建 2 个集合?【英文标题】:How to create 2 collections based from an array with 2 count in PHP? 【发布时间】:2021-10-16 09:11:31 【问题描述】:我知道这是一个基本问题,很抱歉我无法回答,但是如何在 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
非常感谢任何帮助。
【问题讨论】:
【参考方案1】:在您的$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;
【讨论】:
以上是关于如何在 PHP 中从具有 2 个计数的数组创建 2 个集合?的主要内容,如果未能解决你的问题,请参考以下文章
在 Wordpress Admin 中从 PHP 数组创建“下载到 CSV”按钮