Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values of multidimensional array by key without loop

I have this:

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

What I need is: 7", which is the the sum of the f_count column.

I've been trying to figure this out for a couple hours. I thought array_sum() would work, but not with a multidimensional array. So, I've tried figuring out how to isolate the f_counts by unset() or splicing or anything else, but every solution seems to involve a foreach loop. I've messed with array_map, array_walk, and others to no avail. I haven't found a function that works well with multidimensional arrays.

I'm running PHP 5.4.

Can someone please show me how to sum that column without a foreach loop?

If it helps, the f_count values will never be higher than 100, and the uid values will always be greater than 100.


Alternatively, if there's a way to run my query differently such that the array is not multidimensional, that would obviously work as well.

$query = "SELECT f_count, uid FROM users WHERE gid=:gid"; ... $array = $stmt->fetchAll(); 

I'm using PDO.

like image 757
David Avatar asked Apr 22 '13 02:04

David


People also ask

How do you sum all column values in a multidimensional array?

You could use the aggregate function SUM to get the sum of all the f_count directly in your query. You would combine this with $stmt->fetchColumn() to get the value of the first column (which would be the sum) of the first row (which will be the only row since we used an aggregate function).

How do you find the total number of elements in a multidimensional array?

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.


1 Answers

In php 5.5+ you can just used array_column and array_sum like so:

 $value = array_sum(array_column($arr,'f_count')); 
like image 121
Anthony Harley Avatar answered Oct 04 '22 20:10

Anthony Harley