php calculate sum of all values ​​in multidimensional array

WBOY
Release: 2016-08-08 09:22:32
Original
1061 people have browsed it

php built-in function array_sum() function returns the sum of all values ​​in the array, and can only return the sum of one-dimensional arrays;

To calculate the sum of all values ​​in a multi-dimensional array, a custom function is required;

Copy after login
Copy after login

1function get_sum($array) {
2$num = 0;
3foreach($arrayas$k => $v) {
4if(is_array($v)) {
5$num += get_sum($v);
6        }
7    }
8return$num + array_sum($array);
9 }
10 get_sum($array);
Copy after login
Copy after login
Copy after login
 
Copy after login

The above introduces PHP to calculate the sum of all values ​​in a multi-dimensional array, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!