为了账号安全,请及时绑定邮箱和手机立即绑定

我的php计算没有显示结果

我的php计算没有显示结果

PHP
皈依舞 2022-07-02 15:41:21
我有一个非常愚蠢的问题。我正在从 mysql 中提取收入和支出的总额,然后我想从收入中减去支出。由于某种原因,结果不是剩下的,而是显示了收入数字 - 支出数字。代码如下function total_by_type_between_dates($type, $start, $end){    global $uc_con;    $start  = strtotime ($start);    $end    = strtotime ($end);    $sql    = "SELECT SUM(amount) AS total FROM account WHERE `time` > $start && `time` < $end &&  `type` = '$type'";    $result = $uc_con->query($sql);    $row    = $result->fetch_array(MYSQLI_ASSOC);    $total  = number_format((float)$row['total'], 2, '.', '');    echo $total;}function total_expense_between_dates($start, $end){    global $uc_con;    $start  = strtotime ($start);    $end    = strtotime ($end);    $sql    = "SELECT SUM(amount) AS total FROM account WHERE `time` > $start && `time` < $end && `type` != 'income' && `type` != 'mileage'";    $result = $uc_con->query($sql);    $row    = $result->fetch_array(MYSQLI_ASSOC);    $total  = number_format((float)$row['total'], 2, '.', '');    return $total;}echo total_by_type_between_dates('income', $date_begining, $date_ending)-total_expense_between_dates($date_begining, $date_ending);奇怪的是结果显示如下:2770.69-407.42而不是2363.29谁能告诉我可能是什么原因造成的
查看完整描述

1 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

您的total_by_type_between_dates函数正在回显其结果而不是返回它。所以你的

echo total_by_type_between_dates('income', $date_begining, $date_ending)-total_expense_between_dates($date_begining, $date_ending);

有效地

echo total_by_type_between_dates('income', $date_begining, $date_ending);
echo null-total_expense_between_dates($date_begining, $date_ending);

并且null在数字上下文中被视为 0,因此您看到的结果是:2770.69-407.42

改变

echo $total;

total_by_type_between_dates

return $total;

并且代码将按预期工作。

3v4l.org 上的精简演示


查看完整回答
反对 回复 2022-07-02
  • 1 回答
  • 0 关注
  • 199 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号