Sum Values in One Column of a 2D Array
To calculate the sum of values in a specific column of a multidimensional array without using a foreach loop, consider using the following methods:
PHP 5.5 Solution using array_column and array_sum:
$value = array_sum(array_column($arr, 'f_count'));
Alternative Solution Using array_reduce:
$value = array_reduce($arr, function ($carry, $item) { return $carry + $item['f_count']; }, 0);
These methods avoid the need for a foreach loop and provide an efficient way to sum the values in the desired column.
Alternatively, you could modify your query to return a flattened array:
$query = "SELECT f_count from users WHERE gid=:gid"; ... $array = $stmt->fetchAll(\PDO::FETCH_COLUMN);
This would result in a one-dimensional array with only the f_count values, which can then be summed using array_sum.
The above is the detailed content of How Can I Efficiently Sum Values in a Single Column of a 2D Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!