SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
-
Oct 12, 2007, 16:29 #1
Sum of Specific Values in Multi-Dimensional Array
Hi. I have an array that consists mostly of other arrays (so I guess it's a multidimensional array). In fact, only the first element in the main array is NOT an array; the rest of the elements are, and they all contain the same type of data. I need to get the sum of, for example, the 2nd value of all of the arrays. How would I do that? Is there some variation of array_sum that lets you get a sum of values across multiple arrays as opposed to getting a sum of the values in a single array? Thanks for any help!
-
Oct 12, 2007, 17:09 #2
- Join Date
- Sep 2007
- Location
- Vancouver, BC, Canada
- Posts
- 233
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
seems there is no such function you expected.
but this code may help you
suppose the multidimensional array like this
PHP Code:$data = array(
1,
array(2, 3, 4),
array(5, 6),
array(7, 8, 9, 10)
);
PHP Code:function get_second_element(&$data) {
if (is_array($data) && sizeof($data) >= 2) {
return $data[1];
}
}
echo $sum = array_sum(array_map('get_second_element', $data));
* @location Vancouver, BC, Canada
* @name Steve
* @job PHP/MySQL, Drupal, WordPress Developer
-
Oct 12, 2007, 18:18 #3
Perfect. Thanks!!
Bookmarks