Home > Backend Development > PHP Tutorial > How Can I Efficiently Sum Values in a Single Column of a 2D Array in PHP?

How Can I Efficiently Sum Values in a Single Column of a 2D Array in PHP?

Patricia Arquette
Release: 2024-12-10 13:48:15
Original
627 people have browsed it

How Can I Efficiently Sum Values in a Single Column of a 2D Array in PHP?

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'));
Copy after login

Alternative Solution Using array_reduce:

$value = array_reduce($arr, function ($carry, $item) {
    return $carry + $item['f_count'];
}, 0);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template