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 say this method uses PHP SPL Iterators.
Salathe Edit:
A simple (relatively) way to filter keys and sum values (without writing a custom Iterator) would be to do some filtering using RegexIterator , convert the resulting iterator to an array and use the convenient array_sum on it. This is a purely academic exercise, and of course I would not defend it as the best way to achieve this ... however, this 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 ) );
source share