[英]PHPExcel: Read .xlsx file, sum column 'x' values for similar value of column 'y'
I'm stuck on this problem, let me explain. 我被这个问题困扰,让我解释一下。 I've a Excel sheet that has 3 columns like so:
我有一个包含3列的Excel工作表,如下所示:
y x z
10 5 0
10 5 4.25
10 5 0
30 2 0
30 2 1.85
30 2 0
How can I add the values of col.x for the similar values of col.y? 如何为col.y的相似值添加col.x的值?
The desired result is: 理想的结果是:
y=10, x=15
y=30, x=6
Is it possible to achieve this using PHPExcel (if not then what's the best approach)? 是否可以使用PHPExcel来实现(如果没有,那么最好的方法是什么?)?
I tried this but its returning associative array: 我试过了,但是它返回了关联数组:
$objPHPExcel = PHPExcel_IOFactory::load($file_name);
$array = $objPHPExcel->getActiveSheet();
$highestRow = $array->getHighestRow();
$data = $array->rangeToArray("A2:C$highestRow");
$data returns associative array, but that's not what I want. $ data返回关联数组,但这不是我想要的。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
You need walk the array data and sum the items manually 您需要遍历数组数据并手动求和
$objPHPExcel = PHPExcel_IOFactory::load($file_name);
$array = $objPHPExcel->getActiveSheet();
$highestRow = $array->getHighestRow();
$data = $array->rangeToArray("A2:C$highestRow");
$sumData = [];
foreach ($data as $row){
$key = $row[0];
if(!isset($sumData[$key])){
$sumData[$key] = [0, 0];
}
$sumData[$key][0] += $row[1];
$sumData[$key][1] += $row[2];
}
print_r($sumData);
Result: 结果:
Array ( [10] => Array ( [0] => 15 [1] => 4.25 ) [30] => Array ( [0] => 6 [1] => 1.85 ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.