PHP calculates the sum of all values ​​in a multidimensional array, multidimensional array_PHP tutorial

WBOY
Release: 2016-07-13 09:50:28
Original
1134 people have browsed it

php calculates the sum of all values ​​in a multi-dimensional array, multi-dimensional array

php built-in function array_sum() function returns the sum of all values ​​in the array, and can only return the sum of one-dimensional arrays ;

To calculate the sum of all values ​​in a multi-dimensional array, you need to customize a function;

Copy after login
Copy after login
<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);
Copy after login
Copy after login
Copy after login

<span> </span>
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1018253.htmlTechArticlephp calculates the sum of all values ​​in a multi-dimensional array, multi-dimensional array php built-in function array_sum() function returns all values ​​in the array The sum of can only return the sum of one-dimensional arrays; Calculate multi-dimensional numbers...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!