I have a array with values. I want to reduce the amount if someone buys an item. For example if someone buys 45 items I want to loop the array values and calculate with the purchaded items until whats left.
What I tried.
<?php
$purchased = 45;
$stock = array(40, 50, 60);
for( $i = 0; $i < count($stock); $i ){
$left = $stock[$i]-$purchased;
echo $left . "\n";
}
// result: -5, 5, 15
// needs to be: 0, 45, 60
?>
As suggested to show the code. its dutch column names. It has nothing to do with purchasing. I did it in the example to clarify.
$select = $db->prepare("SELECT c.id, d.id AS grondstofid, d.naam,
(a.aantal/b.volume)*c.aantal AS afschrijving
FROM ".DB04.".verkooporderregelstemp AS a
INNER JOIN ".DB02.".recepten AS b ON a.receptid=b.id
INNER JOIN ".DB02.".receptgrondstoffen AS c ON a.receptid=c.receptid
INNER JOIN ".DB02.".grondstoffen AS d ON c.grondstofid=d.id
WHERE a.guid=:guid AND a.productie='1' AND c.grondstofid='1' GROUP BY c.id");
$select->bindValue(":guid", $guid);
$select->execute();
$result = $select->fetchAll();
foreach ($result as $data) {
$grondstofid = $data['grondstofid'];
$afschrijving = $data['afschrijving']; // this is the total reduction
$select1 = $db->prepare("SELECT id, voorraad FROM ".DB02.".grondstofbatch WHERE grondstofid=:grondstofid AND FROM_UNIXTIME(thtdatum)>CURRENT_TIMESTAMP GROUP BY id ORDER BY thtdatum ASC");
$subselect->bindValue(":grondstofid", $grondstofid);
$subselect->execute();
$subresult = $subselect->fetchAll();
foreach ($subresult as $subdata) {
$subdata['voorraad']; // 3 rows
//batch 1 - AMOUNT 40
//batch 2 - AMOUNT 50
//batch 3 - AMOUNT 60
// some loop for $subdata['voorraad']-$afschrijving
// update SQL
// if its hits zero get remaining $afschrijving goto next row
}
}
CodePudding user response:
You can achive that with a simple foreach loop.
$purchased = 45;
$stock = [40, 50, 60];
$newStock = function ($purchased, $stock) {
foreach ($stock as &$item) {
$delta = $item - $purchased;
$item = $delta > 0 ? $delta : 0;
$purchased = $delta < 0 ? abs($delta) : 0;
}
return $stock;
};
print_r($newStock($purchased, $stock));
Output
Array
(
[0] => 0
[1] => 45
[2] => 60
)