我有一个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
答案 0 :(得分:2)
根据manual,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选择总和。
select sum(value) as the_sum from table
然后获取结果并输出the_sum
。
答案 1 :(得分:0)
$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);