Using an optional where condition to filter the result.
$arr = [
['age' => 19, 'first_name' => 'John', 'last_name' => 'Doe'],
['age' => 11, 'first_name' => 'Andrew', 'last_name' => 'Williams'],
['age' => 25, 'first_name' => 'Albert', 'last_name' => 'Taylor'],
['age' => 36.5, 'first_name' => 'Mike', 'last_name' => 'Smith'],
['age' => 33, 'first_name' => 'Andrew', 'last_name' => 'Smith'],
];
X::sum($arr, 'age');
// (float) 19 + 11 + 25 + 36.5 + 33
X::sum($arr, 'age', ['first_name' => 'Andrew']);
// (float) 11 + 33
X::sum($arr, 'age', function ($item) {
return $item['first_name'] === 'John' || $item['first_name'] === 'Mike';
});
// (float) 19 + 36.5
function(array $ar, string $field, $where = NULL)
{
$tot = 0;
if ($res = $where ? self::filter($ar, $where) : $ar) {
foreach ($res as $r) {
$r = (array)$r;
$tot += (float)($r[$field]);
}
}
return $tot;
}