Home > Database > Mysql Tutorial > How to Sum the Values of a Specific Column in a Two-Dimensional Array in PHP?

How to Sum the Values of a Specific Column in a Two-Dimensional Array in PHP?

Linda Hamilton
Release: 2024-12-17 18:29:15
Original
1023 people have browsed it

How to Sum the Values of a Specific Column in a Two-Dimensional Array in PHP?

Summing Values in a Two-Dimensional Array

You have a multidimensional array and need to sum the values in a specific column without using a foreach loop. In PHP 5.5 , you can achieve this efficiently using the array_column and array_sum functions:

array_column($arr, 'f_count')

This extracts the f_count values from the array into a one-dimensional array, preserving their original order. You can then apply:

array_sum($columnArray)

where $columnArray is the array returned by array_column, to sum the extracted f_count values.

For your sample array, this would give you the result:

$value = array_sum(array_column($arr, 'f_count'));
echo $value; // Outputs 7
Copy after login

Note that in earlier PHP versions, you can use a custom function to achieve the same result:

function get_column($array, $column) {
    return array_map(function ($element) use ($column) {
        return $element[$column];
    }, $array);
}

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

The above is the detailed content of How to Sum the Values of a Specific Column in a Two-Dimensional 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