多维数组键值求和,无循环 [英] Sum values of multidimensional array by key without loop

查看:25
本文介绍了多维数组键值求和,无循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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 )
)

我需要的是:7",它是f_count列的总和.

What I need is: 7", which is the the sum of the f_count column.

我已经尝试了几个小时来解决这个问题.我认为 array_sum() 会起作用,但不是多维数组.因此,我尝试弄清楚如何通过 unset() 或拼接或其他任何方式来隔离 f_count s,但每个解决方案似乎都涉及 foreach 循环.我弄乱了 array_maparray_walk 和其他方法,但无济于事.我还没有找到适用于多维数组的函数.

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_counts 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.

我运行的是 PHP 5.4.

I'm running PHP 5.4.

谁能告诉我如何在没有 foreach 循环的情况下对该列求和?

Can someone please show me how to sum that column without a foreach loop?

如果有帮助,f_count 值永远不会高于 100,并且 uid 值将始终大于 100.

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();

我正在使用 PDO.

推荐答案

你需要把它和array_map() 首先选择 f_count 列:

array_sum(array_map(function($item) { 
    return $item['f_count']; 
}, $arr));

当然,在内部,这执行了一个双循环;只是你没有在代码中看到它.您可以使用 array_reduce() 来摆脱一个循环:

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);

然而,如果速度是唯一的兴趣,foreach 仍然是最快的:

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.

这篇关于多维数组键值求和,无循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆