-
-
/**
- desc: array recursive sum
- link: bbs.it-home.org
- date: 2013/2/22
- */
- function arraySumRecursive($array)
- {
- $total = 0;
- foreach(new recursiveIteratorIterator( new recursiveArrayIterator($array) ) as $num)
- {
- $total += $num;
- }
- return $total;
- }
/*** a flat array ***/
- $array = array(10, 20, 5, 34, 129);
/*** add the values ***/
- echo arraySumRecursive($array)."
";
-
/*** a multi dimensional array ***/
- $array = array(10, 20, 5,
- array(5, 2, 3,
- array(5, 3,
- array(2, 10,
- array( 19, 1)
- ),3
- ), 2, 7
- ), 3
- );
/*** add the values ***/
- echo arraySumRecursive($array);
- ?> ;
-
Copy the code
The output of the above script is as follows:
you may also like:
Small examples of php arrays and loops
|