Summing Values in a 2D Array Column without Foreach Loops
In PHP 5.4, it is possible to sum values in a specified column of a 2D array without resorting to foreach loops.
Consider the following multidimensional array:
Array ( [0] => Array ( [f_count] => 1 [uid] => 105 ) [1] => Array ( [f_count] => 0 [uid] => 106 ) [2] => Array ( [f_count] => 2 [uid] => 107 ) [3] => Array ( [f_count] => 0 [uid] => 108 ) [4] => Array ( [f_count] => 1 [uid] => 109 ) [5] => Array ( [f_count] => 0 [uid] => 110 ) [6] => Array ( [f_count] => 3 [uid] => 111 ) )
To sum the values in the "f_count" column, we can utilize the array_column and array_sum functions:
$value = array_sum(array_column($arr,'f_count'));
This method extracts the "f_count" values from the array into a one-dimensional array using array_column, and then sums the values in that array using array_sum, resulting in the sum value of 7.
Alternatively, if you prefer a different SQL query format, you can modify your query to return a one-dimensional array:
$query = "SELECT SUM(f_count) AS f_count_sum FROM users WHERE gid=:gid"; ... $value = $stmt->fetchColumn();
This query returns a single column named "f_count_sum" containing the sum of all "f_count" values, which can then be accessed directly using fetchColumn().
The above is the detailed content of How to Sum a 2D Array Column's Values in PHP without `foreach` Loops?. For more information, please follow other related articles on the PHP Chinese website!