Home >Backend Development >PHP Tutorial >How to Sum a Column's Values in a Multidimensional Array Without a Foreach Loop?

How to Sum a Column's Values in a Multidimensional Array Without a Foreach Loop?

DDD
DDDOriginal
2024-12-22 15:53:11321browse

How to Sum a Column's Values in a Multidimensional Array Without a Foreach Loop?

Sum Value in One Column of a Multidimensional Array

This code query results in a multitude of arrays:

$array = [
    [ 'f_count' => 1, 'uid' => 105 ],
    [ 'f_count' => 0, 'uid' => 106 ],
    [ 'f_count' => 2, 'uid' => 107 ],
    [ 'f_count' => 0, 'uid' => 108 ],
    [ 'f_count' => 1, 'uid' => 109 ],
    [ 'f_count' => 0, 'uid' => 110 ],
    [ 'f_count' => 3, 'uid' => 111 ]
];

The goal is to sum the 'f_count' column without resorting to a foreach loop. For PHP 5.5 versions, there's a simple and elegant solution:

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

array_column extracts a specific column from an array, while array_sum adds the values of an array. Combining these functions seamlessly calculates the sum of the 'f_count' column without the need for a foreach loop.

The above is the detailed content of How to Sum a Column's Values in a Multidimensional Array Without a Foreach Loop?. 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