我从MySQL数据库中提取了一组数字,我正在尝试对它们进行一些简单的数学运算来计算发票中的总价格,但PHP不合作。我认为这可能是类型强制问题,所以我尝试添加一些intval
和floatval
来电,但总数仍然是0。
以下是相关代码。
$totalSum = 0;
$parts = $db->select("*", "WHERE record_id=$id", "recordparts");
foreach($parts as &$part) {
$part['priceTotal'] = (floatval($part['price']) * intval($price['quantity'])) + (floatval($part['laborTime']) * floatval($price['laborRate']));
$totalSum += $part['priceTotal'];
}
$record['parts'] = $parts;
$record['partsSum'] = $totalSum;
以下是上述操作的结果
parts => Array (1)
0 => Array (8)
id => "18"
partNumber => "92-000001"
record_id => "17"
price => "11.5"
laborTime => "2"
laborRate => "65"
quantity => "1"
priceTotal => 0
partsSum => 0
答案 0 :(得分:1)
$parts
切换到使用$price
作为数组。解决了我的问题。
foreach($parts as &$part) {
$price = floatval($part['price']);
$quantity = intval($part['quantity']);
$laborTime = floatval($part['laborTime']);
$laborRate = floatval($part['laborRate']);
$part['priceTotal'] = ($price * $quantity) + ($laborTime * $laborRate);
$totalSum += $part['priceTotal'];
}
答案 1 :(得分:1)
出于好奇,你为什么不让MySQL做乘法呢?我猜这无论如何都会更快。
$totalSum = 0;
$parts = $db->select("*, price * quantity AS priceTotal", "WHERE record_id = $id", "recordparts");
foreach($parts as &$part) {
$totalSum += $part['priceTotal'];
}
$record['parts'] = $parts;
$record['partsSum'] = $totalSum;