Sum values of multidimensional array by key without loop(无循环按键对多维数组的值求和)
问题描述
I have this:
Array (
[0] => Array ( [f_count] => 1 [uid] => 105 )
[1] => Array ( [f_count] => 0 [uid] => 106 )
[2] => Array ( [f_count] => 2 [uid] => 107 )
[3] => Array ( [f_count] => 0 [uid] => 108 )
[4] => Array ( [f_count] => 1 [uid] => 109 )
[5] => Array ( [f_count] => 0 [uid] => 110 )
[6] => Array ( [f_count] => 3 [uid] => 111 )
)
What I need is: 7
", which is the the sum of the f_count
column.
I've been trying to figure this out for a couple hours. I thought array_sum()
would work, but not with a multidimensional array. So, I've tried figuring out how to isolate the f_count
s by unset()
or splicing or anything else, but every solution seems to involve a foreach
loop. I've messed with array_map
, array_walk
, and others to no avail. I haven't found a function that works well with multidimensional arrays.
I'm running PHP 5.4.
Can someone please show me how to sum that column without a foreach
loop?
If it helps, the f_count
values will never be higher than 100
, and the uid
values will always be greater than 100
.
Alternatively, if there's a way to run my query differently such that the array is not multidimensional, that would obviously work as well.
$query = "SELECT f_count, uid FROM users WHERE gid=:gid";
...
$array = $stmt->fetchAll();
I'm using PDO.
You need to couple it with array_map()
to select the f_count
column first:
array_sum(array_map(function($item) {
return $item['f_count'];
}, $arr));
Of course, internally, this performs a double loop; it's just that you don't see it inside the code. You could use array_reduce()
to get rid of one loop:
array_reduce($arr, function(&$res, $item) {
return $res + $item['f_count'];
}, 0);
However, if speed is the only interest, foreach
remains the fastest:
$sum = 0;
foreach ($arr as $item) {
$sum += $item['f_count'];
}
This is thanks to the "locality" of the variables that you're using, i.e. there are no function calls used to calculate the final sum.
这篇关于无循环按键对多维数组的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无循环按键对多维数组的值求和
基础教程推荐
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01