3 回答

TA贡献1829条经验 获得超4个赞
我假设它$product_quantity始终是一个正整数。但也许您想在继续之前检查一下,如下所示:
$product_quantity = $product['quantity']; // this is already in your code
if (!is_int($product_quantity) || $product_quantity < 1) {
// handle the invalid data
}
现在我们确定只处理正整数,我们可以在每次迭代中检查是否没有超过每个订单允许的商品数量:
$total_products = array();
$product_per_order = 0;
foreach($products as $product){
$product_id = $product['sellable']['id'];
$product_quantity = $product['quantity'];
$product_price = $product['price_per_unit'];
while ($product_quantity > 2) {
// handle delivery with 2 products of type $product_id
$product_quantity -= 2;
}
if ($product_quantity <= 0) { // We delivered all of what was ordered
continue;
}
$product_per_order += $product_quantity;
if ($product_per_order > 2) {
// handle more deliveries
$product_per_order = 0; // initialize
}
$total_products[] = array($product_id, $product_quantity, $product_price);
}
这只是跟踪产品数量的方法的概述,您应该改进它并根据自己的需求进行自我定制。

TA贡献1810条经验 获得超5个赞
设法通过使用以下内容来解决这个问题,这给了我我需要的单独的包裹:
// Add the product info we need into a new array
$total_products = array();
foreach($products as $product){
$product_id = $product['sellable']['id'];
$product_quantity = $product['quantity'];
$product_price = $product['price_per_unit'];
$total_products[] = array('id' => $product_id, 'quantity' => $product_quantity, 'price' => $product_price);
}
// Separate out the quantities for each product, one per array
$resultArr = [];
foreach($total_products as $item){
for($i = 0; $i < $item['quantity']; $i++){
$resultArr[] = array(
'id' => $item['id'],
'quantity' => 1,
'price' => $item['price'],
);
}
}
// Divide up into the correct amount of parcels
$parcel_size = 2;
$parcels = array_chunk($resultArr, $parcel_size);

TA贡献1842条经验 获得超21个赞
我相信这满足了将产品拆分为多个订单的要求,但仍保留每个订单中的产品数据:
$orders = [];
$i = 0;
foreach ($products as $product) {
foreach (array_fill(0, ceil($product['quantity'] / 2), $product) as $splitProduct) {
$splitProduct['quantity'] = min(2, $product['quantity']);
$orders[$i][] = $splitProduct;
$total = array_reduce($orders[$i], function ($carry, $product) {
return $carry + $product['quantity'];
}, 0);
if ($total >= 2) {
$i++;
}
}
}
示例1:
输入:
$products[] = ['sellable' => ['id' => 1], 'quantity' => 4, 'price_per_unit' => 0];
输出:
Array
(
[0] => Array
(
[0] => Array
(
[sellable] => Array
(
[id] => 1
)
[quantity] => 2
[price_per_unit] => 0
)
)
[1] => Array
(
[0] => Array
(
[sellable] => Array
(
[id] => 1
)
[quantity] => 2
[price_per_unit] => 0
)
)
)
示例2:
输入:
$products[] = ['sellable' => ['id' => 1], 'quantity' => 2, 'price_per_unit' => 0];
$products[] = ['sellable' => ['id' => 2], 'quantity' => 2, 'price_per_unit' => 0];
输出:
Array
(
[0] => Array
(
[0] => Array
(
[sellable] => Array
(
[id] => 1
)
[quantity] => 2
[price_per_unit] => 0
)
)
[1] => Array
(
[0] => Array
(
[sellable] => Array
(
[id] => 2
)
[quantity] => 2
[price_per_unit] => 0
)
)
)
- 3 回答
- 0 关注
- 114 浏览
添加回答
举报