php - 在PHP中按列查找元素的总和
问题描述
我有这个多维数组:
$dataset = [
[5,15,25],
[15,5,27],
[10,8,16]
]
我的问题是:
数据集可以有任意数量的数组,但数据集中的每个数组将具有相同数量的元素
我想编写一个函数,它将返回一个数组,该数组包含相同索引处的元素总数,即所有第一个数组元素的总数和所有第二个元素的总数等等......在“$total”数组中
示例:
function find_total($dataset){
$total[0]=5+15+10 //total of all the first elements
$total[1]=15+5+8 //total of all the second elements
$total[2]=25+27+16 //total of all the third elements
return $total;
}
解决方案
肯定会有很多简单的答案,但这里有一个复杂的答案(从php5.6 开始):
$dataset = [
[5,15,25],
[15,5,27],
[10,8,16],
];
print_r(array_map('array_sum', array_map(null, ...$dataset)));
推荐阅读
- python - 如何获得熊猫的滞后月平均值
- python - 在 TSP(Miller、Tucker、Zemlin)中实施顺序公式
- tensorflow2.0 - “黑客的贝叶斯方法” jupyter notebook 不工作
- firebase - 有没有办法从最近上传的 Firebase 中获取数据?
- java - 以编程方式创建复合过滤器以在 log4j 2 中定义多个过滤器
- javascript - SQLSTATE [23000]:完整性约束违规:1052 列“created_at”在 order 子句中不明确 Laravel 8
- excel - 将范围作为单独的值复制到剪贴板
- r - 在包开发中使用 data.table 包中的 `[` 方法
- c - 如何从C中的线程退出程序?
- python - AttributeError:“UserViewSet”对象没有属性“用户”