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
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);
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!