note 80697 added to function.array-sum
| From: | djyb2003 at yahoo dot fr | Date: | Tue, 29 Jan 2008 14:31:28 +0000 |
| Subject: | note 80697 added to function.array-sum | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-135545@lists.php.net to get a copy of this message | ||
here is a function that can sum values like these :
$tab = array(
0 => array ("val1" => 2,"val2" => 5)
1 => array ("val1" => 6,"val2" => 10)
"toto" => array ("val1" => 15,"val2" => 50)
);
sum_subarrays_by_key( $tab, "val1" );
the function will sum all values with "val1" key in tab subarrays.
function sum_subarrays_by_key( $tab, $key ) {
$sum = 0;
foreach($tab as $sub_array) {
$sum += $sub_array[$key];
}
return $sum;
}
it can be transformed to be recursive and do also all depths possible in an array.
Hope it can be usefull!
----
Server IP: 69.147.83.197
Probable Submitter: 90.38.3.234
----
Manual Page -- http://www.php.net/manual/en/function.array-sum.php
Edit -- https://master.php.net/note/edit/80697
Del: integrated -- https://master.php.net/note/delete/80697/integrated
Del: useless -- https://master.php.net/note/delete/80697/useless
Del: bad code -- https://master.php.net/note/delete/80697/bad+code
Del: spam -- https://master.php.net/note/delete/80697/spam
Del: non-english -- https://master.php.net/note/delete/80697/non-english
Del: in docs -- https://master.php.net/note/delete/80697/in+docs
Del: other reasons-- https://master.php.net/note/delete/80697
Reject -- https://master.php.net/note/reject/80697
Search -- https://master.php.net/manage/user-notes.php