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

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

问题描述

我有这样的:

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列的总和。
我一直在试图找出这一点的一对夫妇小时。我以为array_sum会的工作,但不能与一个多维数组。于是,我试着找出如何通过取消设置()或剪接或任何其他的f_counts隔离,但是每一个解决方案似乎涉及一个foreach循环。我搞砸与array_map,array_walk,并没有用其他人。我还没有发现用多维数组行之有效的功能。

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_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。

I'm using PDO.

推荐答案

您需要夫妇它 array_map() 首先选择 f_count 列:

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

当然,在内部,这个执行双循环;它只是你没有看到它的code内。你可以使用 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 仍然是最快的:

$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天全站免登陆