F__M
F__M

Reputation: 1598

Sum a single column of a 2d array

I'd like to make a sum of all [Suggested] field values.

[
    [
        'Id' => 4,
        'Suggested' => 1322,
        'proximite_r' => 30924.8470655462,
    ],
    [
        'Id' => 7,
        'Suggested' => 773,
        'proximite_r' => 32229.1036975145,
    ],
]

The total should be: 2095

Upvotes: 0

Views: 2671

Answers (5)

SaidbakR
SaidbakR

Reputation: 13544

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

Upvotes: 0

maček
maček

Reputation: 77778

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.

Upvotes: 8

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

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.

Upvotes: 0

RDK
RDK

Reputation: 4560

You may try this:

$Sum = 0;
foreach ($row as $item) {
   $Sum += $item['Suggested']; // or else index
}
echo $Sum;

Upvotes: 6

alex
alex

Reputation: 490243

$sum = array_sum(
              array_map(function($item) { return $item["Suggested"]; }, $items)
       );

Upvotes: 4

Related Questions