Home >Database >Mysql Tutorial >How to Efficiently Sum Values in a Specific Column of a Multidimensional Array?

How to Efficiently Sum Values in a Specific Column of a Multidimensional Array?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 13:50:54145browse

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:

  • array_column: Extracts a specific column from an array.
  • array_sum: Sums the values in an array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn