数组 array_sum()怎么求不了总和?

WBOY
Release: 2016-06-23 13:57:45
Original
1138 people have browsed it

array_sum()求一个三维数组的总和,结果是0,$count的出来的结果是91125。求各位大神解释一下,谢谢。

 $count=0; $brr=array(); for($i=0;$i<10;$i++){ 	for($j=0;$j<10;$j++) 	{ 		for($k=0;$k<10;$k++) 		{ 			$brr[$i][$j][$k]=$i*$j*$k; 			$count+=$brr[$i][$j][$k]; 		} 	} }var_dump($brr);var_dump($count);var_dump(array_sum($brr));
Copy after login


回复讨论(解决方案)

array_sum不能直接用于多维数组之和吧

array_sum只针对一维数组,你那是多维数组啊

function m_array_sum($ar) {  $r = 0;  foreach($ar as $item) {    if(is_array($item)) $r += m_array_sum($item);  }  return $r + array_sum($ar);}echo m_array_sum($brr);
Copy after login
Copy after login
91125

还真不知道,原来是这么回事,谢谢,才开始看php没几天,所以不知道啊..

function m_array_sum($ar) {  $r = 0;  foreach($ar as $item) {    if(is_array($item)) $r += m_array_sum($item);  }  return $r + array_sum($ar);}echo m_array_sum($brr);
Copy after login
Copy after login
91125


非常感谢!
Related labels:
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