我试图编写一个将订单价值减去多个仓库位置的脚本,取决于每个仓库中订单数量和商品的可用性。
订单表:
item_id | quantity | 1 50
仓库表:
item_id | available | 1 50 1 20
真正的问题:
我的PHP代码:
foreach($warehouse->stocks as $stock) {
if($order->quantity <= $stock->available || $order->quantity === 0) {
$stock->available = $stock->available - $order->quantity;
break;
}
$stock->available = $stock->available - $order->quantity;
}
我的示例数据和所需的输出:
$orderValue = 50; \\this will be the order value
$array = array(50, 20); \\this will be the array inventory values
Output :
$orderValue = 0;
$array = array(0, 20);
----------------------------------
$orderValue = 50; \\this will be the order value
$array = array(25, 20); \\this will be the array inventory values
Output :
$orderValue = 5;
$array = array(0, 0);
----------------------------------
$orderValue = 50; \\this will be the order value
$array = array(52, 10); \\this will be the array inventory values
Output :
$orderValue = 0;
$array = array(2, 10);
----------------------------------
$orderValue = 50; \\this will be the order value
$array = array(20, 25, 25); \\this will be the array inventory values
Output :
$orderValue = 0;
$array = array(0, 0, 20);
答案 0 :(得分:1)
在检查仓库中的可用性时,您需要将场景分开:
如果订单少于或等于可用性
foreach ($warehouse->stocks as $stock)
{
//if order is bigger we "zeroing" warehouse and subtracting from order
if($order->quantity> $stock->available )
{
$order->quantity -= $stock->available;
$stock->available=0;
}
else
{
//if order is less we "zeroing" order and subtracting from warehouse (and exiting cause we dont need to check more warehouses)
$stock->available-=$order->quantity;
$order->quantity =0;
break;
}
}