首页 > 解决方案 > 在PHP中按列查找元素的总和

问题描述

我有这个多维数组:

$dataset = [
[5,15,25],
[15,5,27],
[10,8,16]
]

我的问题是:

  1. 数据集可以有任意数量的数组,但数据集中的每个数组将具有相同数量的元素

  2. 我想编写一个函数,它将返回一个数组,该数组包含相同索引处的元素总数,即所有第一个数组元素的总数和所有第二个元素的总数等等......在“$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;
}

标签: phparraysmultidimensional-array

解决方案


肯定会有很多简单的答案,但这里有一个复杂的答案(从php5.6 开始):

$dataset = [
    [5,15,25],
    [15,5,27],
    [10,8,16],
];

print_r(array_map('array_sum', array_map(null, ...$dataset)));

推荐阅读