Home >Database >Mysql Tutorial >How to Efficiently Sum Values in a Specific Column of a Multidimensional Array?
Sum Values in a Multidimensional Array Column
Multidimensional arrays present a challenge when it comes to summing specific columns. Consider the example array given:
$arr = [ [0] => ['f_count' => 1, 'uid' => 105], [1] => ['f_count' => 0, 'uid' => 106], [2] => ['f_count' => 2, 'uid' => 107], [3] => ['f_count' => 0, 'uid' => 108], [4] => ['f_count' => 1, 'uid' => 109], [5] => ['f_count' => 0, 'uid' => 110], [6] => ['f_count' => 3, 'uid' => 111] ];
The desired output is 7, which is the sum of the f_count column.
Solution Without a Foreach Loop
PHP 5.5 and later provides two functions that simplify this task:
Using these functions, we can obtain the sum without a foreach loop:
$f_count_column = array_column($arr, 'f_count'); $sum = array_sum($f_count_column);
Alternative Approach: Restructuring the Query
Instead of retrieving a multidimensional array, we can restructure the query to return a one-dimensional array:
$query = "SELECT SUM(f_count) AS total_f_count FROM users WHERE gid=:gid"; $stmt = $pdo->prepare($query); $stmt->execute([':gid' => $gid]); $row = $stmt->fetch(PDO::FETCH_ASSOC); $total_f_count = $row['total_f_count'];
The above is the detailed content of How to Efficiently Sum Values in a Specific Column of a Multidimensional Array?. For more information, please follow other related articles on the PHP Chinese website!