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

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

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

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

This example 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 define a custom function;

?

1

2

3

4

5

6

7

8

9

10

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);

1 2

3

4

5

7 8 9 10
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. http://www.bkjia.com/PHPjc/1020892.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1020892.htmlTechArticlephp method to calculate the sum of all values ​​in a multi-dimensional array. This example describes the method of php to calculate the sum of all values ​​in a multi-dimensional array. . Share it with everyone for your reference. The specific implementation method is as follows:...
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