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!