我有一个带产品的数据库,table1包含当前价格,table2包含以前的价格。
我想计算每件商品的价格差异,以及百分比的差异。
由于某种原因,百分比计算不起作用并返回零。
为了确保我的计算本身没问题,我采用了相同的产品,并且在第一个实例中我在获取数据库后定义了项目值,而对于第二个实例,计算直接来自数据库。
只有第一种情况正常,才能恢复-17%
差异。
代码:
<?php
/* database section start */
$mysqli = new mysqli("db","user","pass","db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* database section end */
// Choose Relevant Products, and turn them into an array
$item_array = array(
'item1',
'item1'
);
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product = array();
$result = $mysqli->query("SELECT p.Name, p.now_price, h.was_price FROM table1 p LEFT JOIN table2 h ON p.ProductId = h.ProductId WHERE p.Name IN ('$item_implode') ORDER BY FIELD (p.Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
$product_name = $row['Name'];
// find all keys in $item_array which value is the products
$keys = array_keys($item_array, $product_name);
foreach ($keys as $key) {
// add values for these keys
$product[$key + 1]["Name"] = $row['Name'];
$product[$key + 1]["now_price"] = $row['now_price'];//
$product[$key + 1]["was_price"] = $row['was_price'];
$product[$key + 1]["delta"] = $row['now_price']-$row['was_price'];
$product[$key + 1]["delta_percent"]= $row['delta']/$row['was_price'];
}
}
// Manual definition:
$product[1]["delta"]=$product[1]["now_price"]-$product[1]["was_price"];
$product[1]["delta_percent"]= $product[1]["delta"]/$product[1]["was_price"];
?>
<body>
<?php $i = 1; while ($i <= 2) { ?>
<ul class="listab">
<li>#: <?= $i ?></li>
<li>Now: <?= $product[$i]["now_price"] ?></li>
<li>Was: <?= $product[$i]["was_price"] ?></li>
<li>Diff: <?= $product[$i]["delta"] ?></li>
<li>Per: <?= $product[$i]["delta_percent"] ?></li>
</ul>
<?php $i = $i + 1; } ?>
</body>
</html>
输出:
#: 1
Now: 306.99
Was: 369.99
Diff: -63
Per: -0.170274872294
#: 2
Now: 306.99
Was: 369.99
Diff: -63
Per: 0
答案 0 :(得分:1)
此行中有错误:
$product[$key + 1]["delta_percent"]= $row['delta']/$row['was_price'];
没有$row['delta']
。前面的语句计算了delta,并将其放在$product[$key+1]["delta"]
中。那应该是:
$product[$key + 1]["delta_percent"]= $product[$key+1]["delta"]/$row['was_price'];
顺便说一下,这不是一个百分比,而是一个比例。要获得百分比,您必须乘以100。
您还可以在SQL中计算增量和比率。
$result = $mysqli->query("
SELECT p.Name, p.now_price, h.was_price,
p.now_price - h.was_price as delta, (p.now_price-h.was_price)/h.was_price AS delta_percent
FROM table1 p
LEFT JOIN table2 h ON p.ProductId = h.ProductId
WHERE p.Name IN ('$item_implode')
ORDER BY FIELD (p.Name, '$item_implode');");