In PHP programming, we often deal with array contents. When working with arrays, we sometimes need to sum certain columns in the array. In this article, I will share how to sum specified columns in PHP.
First, let’s look at the following array example:
$data = array( array('name' => 'John', 'age' => 25, 'salary' => 5000), array('name' => 'Sarah', 'age' => 30, 'salary' => 6000), array('name' => 'Jason', 'age' => 35, 'salary' => 7000), array('name' => 'Linda', 'age' => 40, 'salary' => 8000), array('name' => 'David', 'age' => 45, 'salary' => 9000), );
In this array example, we have five elements, each element containsname
,age
andsalary
three keys and values. Now, we want to sum thesalary
columns of this array.
In PHP, we can use thearray_column
function to get a specified column in an array, and then use thearray_sum
function to sum the column. The following is the sample code:
$salaries = array_column($data, 'salary'); $totalSalary = array_sum($salaries); echo 'The total salary is: ' . $totalSalary;
In this sample code, thearray_column
function is used to get thesalary
column in the$data
array. This creates a new array called$salaries
that contains the salaries of all employees. We can then use thearray_sum
function to sum all the elements in the$salaries
array. This creates a total salary variable named$totalSalary
. Finally, we output the summation result through theecho
statement.
Now, let’s see how to sum multiple columns simultaneously in an array. If we want to sum both theage
andsalary
columns, we can use the following code:
$ages = array_column($data, 'age'); $totalAge = array_sum($ages); $salaries = array_column($data, 'salary'); $totalSalary = array_sum($salaries); echo 'The total age is: ' . $totalAge; echo 'The total salary is: ' . $totalSalary;
In this example code, we create two new The arrays$ages
and$salaries
are used to obtain the values of theage
andsalary
columns respectively. We then use thearray_sum
function to sum all the elements in these two arrays. Finally, we output the summation result through theecho
statement.
To summarize, summing specified columns in PHP is very simple. We only need to use two functions:array_column
andarray_sum
. If we need to sum multiple columns, we can use these two functions multiple times and create new arrays separately. Using these functions can help us process array data in PHP quickly and effectively.
The above is the detailed content of How to specify column sum in php array. For more information, please follow other related articles on the PHP Chinese website!