Home  >  Article  >  Backend Development  >  PHP method to calculate the sum of all values ​​in a multidimensional array, multidimensional array_PHP tutorial

PHP method to calculate the sum of all values ​​in a multidimensional array, multidimensional array_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:48:52854browse

How PHP calculates the sum of all values ​​in a multi-dimensional array, multi-dimensional array

The example in this article describes how PHP calculates the sum of all values ​​in a multi-dimensional array. Share it with everyone for your reference. The specific implementation method is as follows:

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, you need to customize a function;

function get_sum($array) {
   $num = 0;
   foreach($array as $k => $v) {
     if(is_array($v)) {
       $num += get_sum($v);
     }
   }
   return $num + array_sum($array);
}
get_sum($array);

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1021082.htmlTechArticlephp method to calculate the sum of all values ​​in a multi-dimensional array, multi-dimensional array This article describes the example of php calculating all values ​​in a multi-dimensional array sum method. Share it with everyone for your reference. Specific implementation method...
Statement:
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