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!
You may try this:
$Sum = 0;
foreach ($row as $item) {
$Sum += $item['Suggested']; // or else index
}
echo $Sum;
$sum = array_sum(
array_map(function($item) { return $item["Suggested"]; }, $items)
);
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.
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.
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');