Home > Backend Development > PHP Tutorial > Example of recursive summation of php arrays

Example of recursive summation of php arrays

WBOY
Release: 2016-07-25 09:04:47
Original
1311 people have browsed it
  1. /**

  2. desc: array recursive sum
  3. link: bbs.it-home.org
  4. date: 2013/2/22
  5. */
  6. function arraySumRecursive($array)
  7. {
  8. $total = 0;
  9. foreach(new recursiveIteratorIterator( new recursiveArrayIterator($array) ) as $num)
  10. {
  11. $total += $num;
  12. }
  13. return $total;
  14. }
  15. /*** a flat array ***/

  16. $array = array(10, 20, 5, 34, 129);
  17. /*** add the values ***/

  18. echo arraySumRecursive($array)."
    ";
  19. /*** a multi dimensional array ***/

  20. $array = array(10, 20, 5,
  21. array(5, 2, 3,
  22. array(5, 3,
  23. array(2, 10,
  24. array( 19, 1)
  25. ),3
  26. ), 2, 7
  27. ), 3
  28. );
  29. /*** add the values ***/

  30. echo arraySumRecursive($array);
  31. ?> ;
Copy the code

The output of the above script is as follows: Example of recursive summation of php arrays you may also like: Small examples of php arrays and loops



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