Recursive sum of php array

I have an array like this:

Array ( [1000] => Array ( [pv] => 36 ) [1101] => Array ( [1102] => Array ( [pv] => 92 ) [pv] => 38 ) [pv] => 64 ) 

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

In this example, the result will be 36+92+38+64 = 240

Thanks for the help.

+4
source share
8 answers

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 ) ); 
+22
source
 function addPV($array){ $sum = 0; foreach($array as $key => $a){ if (is_array($a)){ $sum += addPV($a); }else if($key == 'pv') { $sum += $a; } } return $sum; } 
+10
source

based on @Ali Sattari answer

 function sum($v, $w) { return $v + (is_array($w) ? array_reduce($w, __FUNCTION__) : $w); } 
+6
source

you can use the array_reduce or array_walk_recursive functions and the custom callback function yourself:

 function sum($v, $w) { $v += $w; return $v; } $total = array_reduce($your_array, "sum"); 
+4
source
 $sum = 0; function sumArray($item, $key, &$sum) { if ($key == 'pv') $sum += $item; } array_walk_recursive($array, 'sumArray',&$sum); echo $sum; 
+1
source
 $array = array('1000'=> array('pv'=>36), array('1101' => array('pv'=>92))); $total = 0; foreach(new recursiveIteratorIterator( new recursiveArrayIterator($array)) as $sub) { $total += (int) $sub; } print_r($total); 
+1
source
 function SumRecursiveByKey($array,$key) { $total = 0; foreach($array as $_key => $value) { if(is_array($value)) { $total += SumRecursiveByKey($array,$key); }elseif($_key == $key) { $total += $value; } } return $total; } 

use as

 $summed_items = SumRecursiveByKey($myArray,'pv'); 

This will give you more options for checking alternative keys by swelling.

+1
source
 private function calculateUserGv($userId) { $group = $this->arrayUnder($this->_user_tree, $userId); global $gv; $gv = 0; $gv = $this->gvRecursive($group); return; } private function gvRecursive($group) { global $gv; foreach ($group as $key => $val) { if ($key == 'pv') { $gv += $group[$key]; } else { $this->gvRecursive($val); } } return $gv; } 
-1
source

All Articles