0

I'd like to make a sum of all [Suggested] field. How can I make it please? I use Php.

Array
(
    [0] => Array
        (
            [Id] => 4
            [Suggested] => 1322
            [proximite_r] => 30924.8470655462
        )

    [1] => Array
        (
            [Id] => 7
            [Suggested] => 773
            [proximite_r] => 32229.1036975145
        )
)

Thanks!

F__M
  • 1,518
  • 1
  • 19
  • 34

5 Answers5

8

Here you go, buddie: array_reduce() like a boss

// PHP >= 5.3
$sum = array_reduce($items, function($sum, $item){
  return $sum += $item['Suggested'];
}, 0);

// PHP 5.2
function _sum($sum, $item){
  return $sum += $item['Suggested'];
}
$sum = array_reduce($items, '_sum', 0);

Sadly PHP <= 5.2 does not support closures, so you have to define the function separately.

maček
  • 76,434
  • 37
  • 167
  • 198
6

You may try this:

$Sum = 0;
foreach ($row as $item) {
   $Sum += $item['Suggested']; // or else index
}
echo $Sum;
Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
RDK
  • 4,540
  • 2
  • 20
  • 29
4
$sum = array_sum(
              array_map(function($item) { return $item["Suggested"]; }, $items)
       );
alex
  • 479,566
  • 201
  • 878
  • 984
  • @TomvanderWoerdt What's the overkill about it? – alex Dec 24 '12 at 21:18
  • Overkill agreed; requires iterating through the collection twice. A simple `array_reduce()` as described in my answer will suffice. – maček Dec 24 '12 at 21:18
  • Faster, maybe, but this code is in isolation. Inside of a web application, it's hardly going to be a bottleneck, especially with any disk usage or database access. – alex Dec 24 '12 at 21:29
0

Given the array_column function that will probably arrive in PHP 5.5 :

function array_column($input, $key) {
    if (is_array($key) || !is_array($input)) return array();
    $array = array();
    foreach($input as $v) {
        if(array_key_exists($key, $v)) $array[]=$v[$key];
    }
    return $array;
}

(source: php.net)

You could use this :

$sum = array_sum(array_column($items, 'Suggested'));

Of course, this is major overkill and I only wanted to point out that this is also a way to achieve it.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
0

Another way to iterate through the array is using for loop, Suppose it is $arr:

<?php    
function getSumOfKey($arr, $key){
     $sum = 0;
     for ($i = 0; $i < count($arr); $i++){
      (is_numeric($arr[$i][$key]))? $sum += $arr[$i][$key] : continue;
     }
     return $sum;
    } 
?>

To implement it:

echo 'The sum is: '.getSumOfKey($arr, 'Suggested');
SaidbakR
  • 13,303
  • 20
  • 101
  • 195