I am trying to write a script that calculates a price based upon the quantities.
Database :
pid | prodict | unit | price
1 | coke |100 | 2
2 | coke |100 | 1.8
3 | coke |300 | 1.5
4 | coke | | 1.1
1 | pepsi |100 | 2.2
2 | pepsi |50 | 2
3 | pepsi | | .8
Pid is product id, Product is Product name/Product code. Unit is Incremental unit, or in addition to the existing unit by the number, price is price per unit for incremental unit.
Real Problems:
I was a big fan of For loop and break(bad programming), but now i think i need either if condition or while loop, for both i do not have much confidence.
Thank you in advance
NoteIf you feel difficult to understand the problem, then just assume the income tax calculator, same or similar thing - upto x amount, base tax, then for NEXT y amount, y tax rate, for next z amount, z tax rate more than z, z+ tax
Well, you certainly want to loop through the products first, and then work out a total based on the quantity passed in. Something like this?
// Using PostgreSQL as an example here
$entries = pg_fetch_all(pg_query('SELECT * FROM database ORDER BY prodict, pid ASC'));
// Have the quantities ready;
$quantities = array(
'coke' => 1024,
'pepsi' => 512,
);
// Prepare an array to hold the total values.
$totals = array();
// Loop through the entries in the array in a non-conventional way
while($entry = current($entries)) {
// Get the name of the product from the array
$product = $entry['prodict'];
// And the quantity
$quantity = $quantities[$product];
// Prepare a price for this product starting at zero
$price = 0;
// Now use a do-while to figure out the price
do {
// At this point '$entry' contains information about the pricing for the first 'x' quanitity
$quantityAtThisPrice = $entry['unit'];
// Check the price
$priceForThisUnit = $entry['price'];
// Check we have any quantity remaining of this product
if($quantity > 0) {
// Check if the quantity at this price is null or if that quantity at this price is more than what we have left
if($quantityAtThisPrice === null || $quantityAtThisPrice > $quantity) {
// This means the rest of the quantity is at this price
$price += ($quantity * $priceForThisUnit);
// No more quantity left to price
$quantity = 0;
}
// Otherwise we'll add for this unit, and move on to the next
else {
// Add to the price
$price += ($quantityAtThisPrice * $priceForThisUnit);
// Subtract the quantity we just priced
$quantity -= $quantityAtThisPrice;
}
}
// Now fetch the next entry
$entry = next($entries);
} while ($entry['prodict'] === $product);
// Add the calculated price to the totals array
$totals[$product] = $price;
}
var_dump($totals);
Got a bit carried away but I think that should work.