Php根据请求值更新和减去数组值

时间:2016-07-04 08:46:48

标签: php arrays algorithm foreach

我试图编写一个将订单价值减去多个仓库位置的脚本,取决于每个仓库中订单数量和商品的可用性。

订单表:

item_id | quantity |
   1         50

仓库表:

item_id | available |
   1         50
   1         20

真正的问题:

  • 如果订单值=商品的可用性,则仓库中商品的可用性变为0。
  • 如果仓库中没有可用物品,
  • 循环将会中断。
  • 根据商品的可用性和订单价值之间的差异更新库存值。

我的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);

1 个答案:

答案 0 :(得分:1)

在检查仓库中的可用性时,您需要将场景分开:

  1. 如果订单大于可用性。
  2. 如果订单少于或等于可用性

      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;
              }
         }