Home >Backend Development >PHP Tutorial >php 计算多维数组中所有值的总数

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

WBOY
WBOYOriginal
2016-06-13 12:22:081054browse

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

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

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


<span style="color: #008080;">1</span> <span style="color: #0000ff;">function</span> get_sum(<span style="color: #800080;">$array</span><span style="color: #000000;">) {</span><span style="color: #008080;">2</span>     <span style="color: #800080;">$num</span> = 0<span style="color: #000000;">;</span><span style="color: #008080;">3</span>     <span style="color: #0000ff;">foreach</span>(<span style="color: #800080;">$array</span> <span style="color: #0000ff;">as</span> <span style="color: #800080;">$k</span> => <span style="color: #800080;">$v</span><span style="color: #000000;">) {</span><span style="color: #008080;">4</span>         <span style="color: #0000ff;">if</span>(<span style="color: #008080;">is_array</span>(<span style="color: #800080;">$v</span><span style="color: #000000;">)) {</span><span style="color: #008080;">5</span>             <span style="color: #800080;">$num</span> += get_sum(<span style="color: #800080;">$v</span><span style="color: #000000;">);</span><span style="color: #008080;">6</span> <span style="color: #000000;">        }</span><span style="color: #008080;">7</span> <span style="color: #000000;">    }</span><span style="color: #008080;">8</span>     <span style="color: #0000ff;">return</span> <span style="color: #800080;">$num</span> + <span style="color: #008080;">array_sum</span>(<span style="color: #800080;">$array</span><span style="color: #000000;">);</span><span style="color: #008080;">9</span> }<br><span style="color: #008080;">10</span> get_sum($array);

 

<span style="color: #ff6600;"> </span>
Statement:
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