Summing Column Values in a Multidimensional Array without Foreach Loops
To calculate the sum of the 'f_count' column in your multidimensional array, you can leverage PHP's array_sum() and array_column() functions without resorting to foreach loops.
PHP 5.5 Solution:
If you're using PHP 5.5 or later, you can simplify the process:
$sum = array_sum(array_column($arr, 'f_count'));
The array_column() function extracts the 'f_count' values into a single-dimensional array, and array_sum() calculates the total.
Alternatively, for MySQL Results:
If you're populating your array from a MySQL query, you can optimize the query to retrieve the sum directly:
$stmt = $db->prepare("SELECT SUM(f_count) AS f_count_total FROM users WHERE gid=:gid"); $stmt->bindParam(':gid', $gid); $stmt->execute(); $row = $stmt->fetch(); $sum = $row['f_count_total'];
The above is the detailed content of How to Sum a Column in a Multidimensional Array in PHP Without Using Foreach Loops?. For more information, please follow other related articles on the PHP Chinese website!