我正在使用像这样的Array_sum
<?php
$totalAmount = $db->prepare('SELECT
a.proId, a.userId,
b.id, b.pPrice
FROM purchaseshistory AS a
INNER JOIN products AS b ON(a.proId=b.id)
WHERE a.userId=?');
$totalAmount->bind_param('i', $cus['cId']);
$totalAmount->execute();
$totalAmount->bind_result($proId, $userId, $id, $pPrice);
$totalAmount->store_result();
while ($totalAmount->fetch()) {
$sum = 0;
$amount = $pPrice;
$amount = is_array($amount) ? $amount : array($amount);
foreach ($amount as $item => $value) {
$sum += $value;
}
print $sum;
}
?>
并试图像这样做
while ($totalAmount->fetch()) {
$amount = array($pPrice);
print array_sum($amount) ;
}
相同的结果我得到像200150200这样的数字
答案 0 :(得分:0)
$amount = [];
while ($totalAmount->fetch()) {
$amount[] = $pPrice;
}
echo array_sum($amount);
你没有向数组添加元素..上面的代码是,并且应该按预期工作
旧版PHP版本的更新
$amount = array();
while ($totalAmount->fetch()) {
$amount[] = $pPrice;
}
echo array_sum($amount);
答案 1 :(得分:0)
另一种选择(不使用array_sum()): -
$sum = 0;
while ($totalAmount->fetch()) {
$sum += $pPrice;
}
echo $sum;