首頁 >php教程 >php手册 >php 计算多维数组中所有值的总和,多维数组

php 计算多维数组中所有值的总和,多维数组

WBOY
WBOY原創
2016-06-13 09:01:15897瀏覽

php 计算多维数组中所有值的总和,多维数组

php 内置函数 array_sum() 函数返回数组中所有值的总和,只能返回一维数组的总和;

计算多维数组所有值的和就要自定义函数了;



<span>1</span> <span>function</span> get_sum(<span>$array</span><span>) {
</span><span>2</span>     <span>$num</span> = 0<span>;
</span><span>3</span>     <span>foreach</span>(<span>$array</span> <span>as</span> <span>$k</span> => <span>$v</span><span>) {
</span><span>4</span>         <span>if</span>(<span>is_array</span>(<span>$v</span><span>)) {
</span><span>5</span>             <span>$num</span> += get_sum(<span>$v</span><span>);
</span><span>6</span> <span>        }
</span><span>7</span> <span>    }
</span><span>8</span>     <span>return</span> <span>$num</span> + <span>array_sum</span>(<span>$array</span><span>);
</span><span>9</span> }<br /><span>10</span> get_sum($array);

 

<span> </span>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn