Home > Article > Backend Development > How to sum a column of a multidimensional array in php
Sum method: 1. Use array_column() to obtain all elements of a specified column in a multi-dimensional array. The syntax "rray_column(array, 'specified column name')" will return a result array containing all elements; 2. Use "array_sum (result array)" to calculate the sum of all elements in the result array.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php for multi-dimensional arrays Method of summing a certain column
In PHP, you can use array_column() and array_sum() to sum a certain column of a multi-dimensional array.
1. Use array_column() to obtain all elements of a specified column
array_column() can return the value of a single column in the specified array; it will be returned An array, the array value is the value of a specified column.
<?php header('content-type:text/html;charset=utf-8'); $arr=array( array( 'month' => "1", 'days' => 31, ), array( 'month' => "2", 'days' => 28, ), array( 'month' => "3", 'days' => 31, ), array( 'month' => "4", 'days' => 30, ), array( 'month' => "5", 'days' => 31, ) ); var_dump($arr); $days=array_column($arr, 'days'); var_dump($days); ?>
2. Use array_sum() to sum the result array
array_sum() function can calculate all elements in the specified array The sum of
echo "多维数组中days列的和:".array_sum($days);
we use a calculator to check:
Recommended learning: "PHP Video Tutorial》
The above is the detailed content of How to sum a column of a multidimensional array in php. For more information, please follow other related articles on the PHP Chinese website!