Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 36+92+38+64 = 240

Thanks for help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
423 views
Welcome To Ask or Share your Answers For Others

1 Answer

Another alternative:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...