0

I have an mysql table named example.

 Id   | Amount  | Left | Filled
 1    |  1      |  1   | 0
 2    |  4      |  4   | 0
 5    |  7      |  7   | 0

I have an variable named $var = 9 Now I have an array named $array with those ids as array([0] => 1, [1] => 2, [2] => 5) Which itself is a mysql result. How do I make a loop so that ids in array keep subtracting the left and keep filling as per the amount but within the total value of $var so that my end result in table is

 Id   | Amount  | Left | Filled
 1    |  1      |  0   | 1
 2    |  4      |  0   | 4
 5    |  7      |  3   | 4

1 Answers1

0

You can use while loop in order to loop on the ids and reduce the amount in each iteration.

I am not sure how you access your DB so I leave it pseudo.

Consider the following code:

$ids = array(1,2,5);
$value = 9;

function reduceAmount($id, $value) {
    $query = mysqli_query($conn, "SELECT * FROM example WHERE Id='$id'");
    $row = mysqli_fetch_array($query);     
    $take = min($row['Left'], $value); // the amount you can take (not more then what left)

    $left = $row['Left'] - $take;
    $filled = $row['Filled'] + $take;
    $conn->query("UPDATE example SET Left='$left', Filled='$filled' WHERE Id='$id'")
    return max(0, $value - $take);
}

while ($value > 0 && !empty($ids)) { // check if value still high and the options ids not finish
    $id = array_shift($ids); //get first ID
    $value = reduceAmount($id, $value);
}

You can check at the end of the loop if value still bigger then 0 - this can happen when no enough "Amount" in ids

dWinder
  • 11,597
  • 3
  • 24
  • 39