/** - desc:数组递归求和
- 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);
- ?>
以上脚本的输出结果如下:
猜你喜欢:
有关php数组及循环的小例子 |