按键求和 multimendion 数组中的元素

Sum elements from multimendion array by key

我想根据列

对数组中的所有元素求和

我尝试计算这个总和,但不是预期的结果。

我的阵列:

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
    )

这个想法实际上是按周期对所有元素进行求和,return 只有一个数组按周期将包含该周期每个元素的总和。

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

$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()删除了密钥。