我正在尝试编写一个根据数量计算价格的脚本。
数据库:
pid | prodict |单位|价钱
1 |可乐| 100 | 2
2 |可乐| 100 | 1.8
3 |可乐| 300 | 1.5
4 |焦炭| | 1.1
1 |百事可乐| 100 | 2.2
2 |百事可乐| 50 | 2
3 |百事| | 0.8
Pid是产品ID,产品是产品名称/产品代码。 单位为增量单位,或者除了现有单位的数量,价格是增量单位的每单位价格。
真正的问题:
我是For循环和破坏(糟糕的编程)的忠实粉丝,但现在我认为我需要条件或while循环,因为我没有太多信心。
提前谢谢
注意如果您觉得难以理解问题,那么只需假设所得税计算器,相同或类似的东西 - 高达x金额,基本税,然后是下一个y金额,y税率,下一个z金额,z税率超过z,z +税
答案 0 :(得分:0)
嗯,您当然希望首先循环使用这些产品,然后根据传入的数量计算总数。这样的东西?
// 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);
有点被带走但我觉得应该有用。