Sum elements from multimendion array by key

半腔热情 提交于 2019-12-10 23:36:18

问题


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

I try to make this sum but not expected results.

My array :

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
    )
)

I try like this :

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

But not work I expected.

The expected result is :

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.


回答1:


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));

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



来源:https://stackoverflow.com/questions/53955018/sum-elements-from-multimendion-array-by-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!