gpt4 book ai didi

php - 添加数组的所有值并将其呈现在数组中的问题

转载 作者:行者123 更新时间:2023-11-29 09:38:08 25 4
gpt4 key购买 nike

我有以下 PHP 脚本,它在数组中显示 numValue 值,然后将 numvalue 的所有值加在一起,并将它们显示为数组中名为 sumTotal< 的另一个项目.

以下是我得到的 JSON 数组的最终结果:

[{"name":"person1","numValue":3.32},{"name":"person2","numValue":2.20},{"sumTotal":5}]

问题是 sumTotal 由于某种原因不考虑小数,而是仅将整数值相加,如上面所示的 3 和 2。

[{"name":"person1","numValue":3.32},{"name":"person2","numValue":2.20},{"sumTotal":5.52}]

哪里做错了?

if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "SELECT name, SUM(value) as numvalue
FROM Table1
LEFT JOIN Table2 USING(DevName)
WHERE name <> ''
and name is not null
GROUP BY name";

if ($result = mysqli_query($con, $sql)) {

$resultArray = array();
$tempArray = array();

// you want an array of objects, so create an object to sum the sub totals
$total = new stdClass;
$total->sumTotal = 0;

while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($resultArray, $tempArray);

$total->sumTotal = bcadd($total->sumTotal, $row->numvalue);
}

$resultArray[] = $total;
echo json_encode($resultArray,JSON_NUMERIC_CHECK);
}

mysqli_close($con);

最佳答案

来自manual

bcadd ( string $left_operand , string $right_operand [, int $scale = 0 ] ) : string

哪里...

scale This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.

所以你应该能够使用以下方法将其修复为小数点后两位

bcscale(2);

在调用bcadd()之前。

一个细微的变化是,由于 bcadd() 需要字符串,因此您应该将初始值更改为字符串...

$total->sumTotal = "0";

关于php - 添加数组的所有值并将其呈现在数组中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57170569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com