按键求和多维数组中的元素 [英] Sum elements from multimendion array by key

查看:86
本文介绍了按键求和多维数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于列对数组中的所有元素求和

I want to sum all elements from my array based on column

我尝试求和,但未达到预期结果.

I try to make this sum but not expected results.

我的数组:

Array
(
[0] => Array
    (
        [Periode] => 2008/2009
        [Producteurs] => 2
        [Sucreries] => 0
        [Papeteries] => 0
    )

[1] => Array
    (
        [Periode] => 2008/2009
        [Producteurs] => 0
        [Sucreries] => 0
        [Papeteries] => 5
    )

[2] => Array
    (
        [Periode] => 2008/2009
        [Producteurs] => 0
        [Sucreries] => 14
        [Papeteries] => 0
    )

[3] => Array
    (
        [Periode] => 2009/2010
        [Producteurs] => 2
        [Sucreries] => 0
        [Papeteries] => 0
    )

[4] => Array
    (
        [Periode] => 2009/2010
        [Producteurs] => 0
        [Sucreries] => 0
        [Papeteries] => 4
    )

[5] => Array
    (
        [Periode] => 2009/2010
        [Producteurs] => 0
        [Sucreries] => 13
        [Papeteries] => 0
    )
)

我这样尝试:

 foreach ($result as $value){
    $result[$value]['Periode'] = $result[$value]['Producteurs'] + $result[$value]['Sucreries'] + $result[$value]['Papeteries'];
 }

但是我没想到.

预期结果是:

Array
(
   [0] => Array
    (
        [Periode] => 2008/2009
        [Producteurs] => 2
        [Sucreries] => 14
        [Papeteries] => 5
    ),
   [1] => Array
    (
        [Periode] => 2009/2010
        [Producteurs] => 2
        [Sucreries] => 13
        [Papeteries] => 4
    )

实际上,我们的想法是按周期对所有元素进行求和,然后仅按周期返回一个数组,其中将包含此周期中每个元素的总和.

The idea in fact is to sum all elements group by periode and return only one array by period that will contains the sum of each element for this periode.

推荐答案

您正在尝试将所有总计加到一个值中并将它们放入一个数组中,我什至不知道该数组的结构.您应该建立一组由'Periode'索引的条目,然后在遇到新元素时将值添加到其中...

You are trying to add up all of the totals into one value and putting them into an array, which I'm not even sure how it will be structured. You should build up a set of entries indexed by the 'Periode' and then add the values into these as you encounter new elements...

$totals = array();
foreach ( $result as $value )   {
    if ( !isset($totals[$value['Periode']]))    {
        $totals[$value['Periode']] = $value;
    }
    else    {
        $totals[$value['Periode']]['Producteurs'] +=$value['Producteurs'];
        $totals[$value['Periode']]['Sucreries'] +=$value['Sucreries'];
        $totals[$value['Periode']]['Papeteries'] +=$value['Papeteries'];
    }
}

print_r(array_values($totals));

我使用array_values()移除键的最终结果.

The end result I use array_values() on to remove the keys.

这篇关于按键求和多维数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆