php数组递归求和 [英] php array recursive sum

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

问题描述

我有一个这样的数组:

Array
(
    [1000] => Array
        (
            [pv] => 36
        )

    [1101] => Array
        (
            [1102] => Array
                (
                    [pv] => 92
                )

            [pv] => 38
        )

    [pv] => 64
)

无论它们出现的深度如何,我如何找到键为pv"的所有数组元素的总和.

How I can find the sum of all array elements with key 'pv', regardless of the depth at which they appear.

对于这个例子,结果将 36+92+38+64 = 240

For this example the result will 36+92+38+64 = 240

感谢您的帮助.

推荐答案

另一种选择:

$sum = 0;
$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($array_obj as $key => $value) {
    if($key == 'pv')
        $sum += $value;
}
echo $sum;

更新: 只是想我会提到这个方法使用 PHP SPL 迭代器.

Update: Just thought I'd mention that this method uses the PHP SPL Iterators.

萨拉特

一个简单的(相对)过滤键和求和值的方法(不编写自定义迭代器)是使用 RegexIterator 进行一些过滤,将结果迭代器转换为一个数组,然后在其上使用方便的 array_sum 函数.这纯粹是一种学术练习,我当然不会提倡将其作为实现这一目标的最佳方式……然而,它只是一行代码.:)

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 handy array_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. :)

$sum = array_sum(
    iterator_to_array(
        new RegexIterator(
            new RecursiveIteratorIterator(
                new RecursiveArrayIterator($array)
            ),
            '/^pv$/D',
            RegexIterator::MATCH,
            RegexIterator::USE_KEY
        ),
        false
    )
);

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

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