所以我有一个在 PHP 中返回以下结果的查询,我正在尝试添加 hours_played
的总数,我已经尝试了 array_sum()
但是这似乎不起作用,我希望能够将 hours_played
的值添加为 11 这样我就可以将它传递给另一个函数:
Array
(
[id] => 1
[team_id] => 1
[hours_played] => 1
)
Array
(
[id] => 2
[team_id] => 1
[hours_played] => 4
)
Array
(
[id] => 3
[team_id] => 1
[hours_played] => 6
)
我有点迷路了,我是否需要将可用的数组存储在另一个数组中才能执行此操作?上面的结果来自 sql 查询,是当我 print_r
$row
变量时打印在页面上的结果。
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
print_r($row);
}
最佳答案
您可以在获取结果并将它们分配到数组后对所有列 hours_played
求和,如下所示
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($res)){
$result[] = $row;
}
$sum = array_sum(array_column($result, "hours_played"));
echo $sum;
..或者您可以在循环结果时对其进行总结。
$sql = "SELECT * FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$sum = 0;
while($row = mysql_fetch_assoc($res)){
$sum += $row['hours_played'];
}
echo $sum;
或者,如果您只需要播放的总小时数,您可以直接在一个查询中完成,使用 MySQL 中的 COUNT()
。
$sql = "SELECT SUM(hours_played) as sum_hours_played FROM table1 WHERE team_id = 1";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
echo $row['sum_hours_played'];
警告
Do not use mysql_*
functions in new code .它们不再维护 and are officially deprecated .
查看red box ?
了解 prepared statements相反,并使用 PDO或 MySQLi
- this article可以帮助您决定选择哪个。
关于php - 不同数组中键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54894073/