Home > Database > Mysql Tutorial > How to Sum a 2D Array Column's Values in PHP without `foreach` Loops?

How to Sum a 2D Array Column's Values in PHP without `foreach` Loops?

Linda Hamilton
Release: 2024-12-13 12:08:11
Original
576 people have browsed it

How to Sum a 2D Array Column's Values in PHP without `foreach` Loops?

Summing Values in a 2D Array Column without Foreach Loops

In PHP 5.4, it is possible to sum values in a specified column of a 2D array without resorting to foreach loops.

Consider the following multidimensional array:

Array (
    [0] => Array ( [f_count] => 1 [uid] => 105 )
    [1] => Array ( [f_count] => 0 [uid] => 106 )
    [2] => Array ( [f_count] => 2 [uid] => 107 )
    [3] => Array ( [f_count] => 0 [uid] => 108 )
    [4] => Array ( [f_count] => 1 [uid] => 109 )
    [5] => Array ( [f_count] => 0 [uid] => 110 )
    [6] => Array ( [f_count] => 3 [uid] => 111 )
)
Copy after login

To sum the values in the "f_count" column, we can utilize the array_column and array_sum functions:

$value = array_sum(array_column($arr,'f_count'));
Copy after login

This method extracts the "f_count" values from the array into a one-dimensional array using array_column, and then sums the values in that array using array_sum, resulting in the sum value of 7.

Alternatively, if you prefer a different SQL query format, you can modify your query to return a one-dimensional array:

$query = "SELECT SUM(f_count) AS f_count_sum FROM users WHERE gid=:gid";
...
$value = $stmt->fetchColumn();
Copy after login

This query returns a single column named "f_count_sum" containing the sum of all "f_count" values, which can then be accessed directly using fetchColumn().

The above is the detailed content of How to Sum a 2D Array Column's Values in PHP without `foreach` Loops?. 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