Your Location is: Home > Php

Unrest value in a 'foreach' loop

From: Poland View: 3050 Yousef Altaf 

Question

I have an order like this

product quantity inventory
   1       5        50
   1       6        50
   7       2        150
   1       6        50

I am trying to loop in each product and decrease the inventory

Total inventory for product 1 is 50

in loop

product 1 the inventory become 45
product 1 the inventory becomes 39
product 7 the inventory becomes 148
product 1 the inventory becomes 44

Hers is the issue in the last loop the inventory has been rest to 50 again.

here is my code

foreach($order->productId->inventory as $currentRequestedCount){
     $currentRequested = $order->quantity * $order->relatedPackage ->unit_count;
        if($currentRequestedCount->type == "existing"){
            $currentRequested -= $currentRequestedCount->amount;
        }
}

how to prevent the $currentRequestedCount from being reset?

Best answer

I use arrays to illustrate this. You have your inventory:

$inventory = [
  //product => inventory
  1 => 50,
  7 => 150,
];

You get a few orders:

$order = [
  ['product' => 1, 'quantity' => 5],
  ['product' => 1, 'quantity' => 6],
  ['product' => 7, 'quantity' => 2],
  ['product' => 1, 'quantity' => 6],
];

The orders are processed (without handling errors!).

foreach($order as $row){
  $inventory[$row['product']] -= $row['quantity'];
}

The current inventory:

var_dump($inventory);

Output:

array(2) {
  [1]=>
  int(33)
  [7]=>
  int(148)
}