求和数组中的所有值并输出结果


Sum All Values in Array and Output Result

我有一个SQL查询,它输出下表:

表包含

Customer  | Value
Customer1 | 50
Customer2 | 1354

我希望使用array_sum对表中的两个值求和。

我的当前代码:

$query = "SELECT * FROM table";
$stmt = sqlsrv_query($conn, $query);
$data = sqlsrv_fetch_array($stmt);
$total = array_sum($data['Value']);
echo $total;

我得到以下错误:

array_sum() expects parameter 1 to be array, double given in etc

根据手册,array_sum需要一个数组,而不是字符串。

您的代码目前也只能处理一条记录。您需要循环提取以获取所有记录。

这应该会给你总数。

$query = "SELECT * FROM table";
$stmt = sqlsrv_query($conn, $query);
$total = 0;
while($data = sqlsrv_fetch_array($stmt)) {
     $total += $data['Value'];
    //other stuff you are doing with results, otherwise just do SQL sum.
}
echo $total;

另一种方法是通过sql选择sum。

select sum(value) as the_sum from table

然后获取结果并输出CCD_ 2。

$sum = array();
$users = array();
$query = "SELECT * FROM table";
$stmt = sqlsrv_query($conn, $query);
$data = sqlsrv_fetch_array($stmt);
while ($row = sqlsrv_fetch_array($result)) {
    $users[] = $row;
}
foreach ($users as $user) {
    $sum[] = $user['value'];
}
echo $total = array_sum($sum);