/ Published in: PHP
Sum all elements of a bidimensional or multi-dimensional array with an assigned key
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * sum values in array * * @param array $arr * @param string [optional]$index * @return int result */ function array_sum_key( $arr, $index = null ){ return 0; } $ret = 0; foreach( $arr as $id => $data ){ }else{ $ret += $data; } } return $ret; } //## To sum elements on a multidimensional finding defined key = 'pv' array $sum = 0; $array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); foreach($array_obj as $key => $value) { if($key == 'pv') $sum += $value; } echo $sum;