如何递归地对特定数组键的所有值求和?
我有一个像这样的数组:
Array
(
[1000] => Array
(
[pv] => 36
)
[1101] => Array
(
[1102] => Array
(
[pv] => 92
)
[pv] => 38
)
[pv] => 64
)
如何找到带有键“pv”的所有数组元素的总和,无论它们出现的深度如何?
对于此示例,结果将为 36+92+38+64 = 230
I have an array like this:
Array
(
[1000] => Array
(
[pv] => 36
)
[1101] => Array
(
[1102] => Array
(
[pv] => 92
)
[pv] => 38
)
[pv] => 64
)
How I can find the sum of all array elements with key 'pv', regardless of the depth at which they appear?
For this example the result will be 36+92+38+64 = 230
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
另一种选择:
更新: 只是想我会提到此方法使用 PHP SPL 迭代器。
Salathe 编辑:
过滤键并对值求和(无需编写自定义迭代器)的一种简单(相对)方法是使用
RegexIterator
,将生成的迭代器转换为数组,并对其使用方便的array_sum
函数。这纯粹是一项学术练习,我当然不会提倡将其作为实现这一目标的最佳方式......但是,它只是一行代码。 :)Another alternative:
Update: Just thought I'd mention that this method uses the PHP SPL Iterators.
Salathe Edit:
A simple (relatively) way to filter the keys and to sum the values (without writing a custom Iterator) would be to do some filtering with a
RegexIterator
, convert the resulting iterator into an array and use the handyarray_sum
function on it. This is purely an academic exercise and I certainly wouldn't advocate it as the best way to achieve this... however, it is just one line-of-code. :)基于@Ali Sattari答案
based on @Ali Sattari answer
您可以使用 array_reduce 或 array_walk_recursive 函数以及您自己的自定义回调函数:
you can use
array_reduce
orarray_walk_recursive
functions and a custom call back function of yourself:使用 like
这会给你更多的余地来检查替代键的膨胀。
use like
This would give you more leeway in checking alternative keys a swell.