php - 不同数组中键的值

标签 php mysql arrays array-sum

所以我有一个在 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相反,并使用 PDOMySQLi - this article可以帮助您决定选择哪个。

关于php - 不同数组中键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54894073/

相关文章:

PHP:更改密码

php - 类型提示和默认参数值也是方法签名吗?

mysql - 无法在 where 子句中使用日期条件执行 mysqldump

mysql - 向 MySQL 添加表不断抛出错误

javascript - 对可能没有直接重叠的多个重叠时间 block 进行分组

php - COUNT = 0 的 Doctrine2 DQL 问题

php - 转换为准备好的语句 - 如何回显查询结果

java - Android如何构造与此类似的字节数组

javascript - 如何获取数组中对象的属性值数组

php - 如何将 [link](#) 替换为 <a href ="#">link</a>?