标题说明了一切:php 中是否有一个垂直求和函数,它在整个数组上添加一个(子)数组值,如下所示:
// pseudo code that would return the sum of "income" for all days of the year
// for example
vertical_sum($array[$day_of_year]["income"]);
标题说明了一切:php 中是否有一个垂直求和函数,它在整个数组上添加一个(子)数组值,如下所示:
// pseudo code that would return the sum of "income" for all days of the year
// for example
vertical_sum($array[$day_of_year]["income"]);
您可以从每个数组中提取income
字段,然后使用array_sum
.
function vertical_sum($array, $key){
return array_sum(array_map(function($a) use($key){
return $a[$key];
}, $array));
}
然后你可以这样称呼它:
vertical_sum($array, "income");
原生功能?不完全是,但数组减少可以帮助:
$array = array(
array('income' => 1), //day 1
array('income' => 3), //day 2, etc
array('income' => 6),
array('income' => 7)
);
echo array_reduce($array, function($curr_total, $this_val) {
return $curr_total + $this_val['income'];
}, 0); //17