按键求和多维数组中的元素

时间:2018-12-28 07:21:34

标签: php arrays php-5.3

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

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

我的数组:

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
    )

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

1 个答案:

答案 0 :(得分:4)

您试图将所有总计加到一个值中并将它们放入一个数组中,我什至不确定如何将其构造。您应该建立一组由'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()移除键的最终结果。