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>
以上就介紹了php 計算多維數組中所有值的總和,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。