sum of duplicated values in nested array php

左心房为你撑大大i 提交于 2020-01-25 17:34:49

问题


I have this array :

 $data =    Array
    (     
        [1] => Array
            (
                [id] => '52040344'
                [outcome] => 0
                [names] => Array
                    (
                      [name_eng] => 'this is a name 2' 
                    )    
            )

        [2] => Array
            (
                [id] => 54030157
                [outcome] => 1108541
                [names] => Array
                    (
                         [name_eng] => 'this is a name 1' 
                    )    
            )

        [3] => Array
            (
                [id] => '54030157
                [outcome] => '109635'
                [names] => Array
                    (
                        [name_eng] => 'this is a name 1' 
                    )
            )
    )

i want to to return an array with the sum of all outcome having the same id, knowing that if they have same id, they have same name.

so i can get

array (
    [0] => array( 'id' => '54030157', 'outcome' => 'sum of outcome', 'name' => 'this is name 1' ),
    [1] => array(  'id' => '52040344', 'outcome' => 'sum of outcome', 'name' => 'this is name 2' )
)

how can i get this done ??.

here is what i have tried so far :

 public function process($data){                        
        $outputArray = array();

        foreach ($data as $key => $value) {                                 

        }            
         return $outputArray;
    }

any help would be appreciated


回答1:


Edit : Answered before update of original answer! Not taken notice of some special constructed output array, but only the calculation of outcome.

Here is a little function you can use :

function computeOutcome($array) {
    $result=array();
    foreach ($array as $item) {
        $id=$item['id'];
        if (isset($result[$id])) {
            $result[$id]=$result[$id]+$item['outcome'];
        } else {
            $result[$id]=$item['outcome'];
        }
    }
    return $result;
}

Pass your multidimensional array as parameter. Test example :

$test=array(
    array('id'=>100, 'outcome'=>'45'),
    array('id'=>200, 'outcome'=>'66'),
    array('id'=>100, 'outcome'=>'88'),
    array('id'=>200, 'outcome'=>'45')
);
print_r(computeOutcome($test));

outputs

Array
(
    [100] => 133
    [200] => 111
)



回答2:


Or you can use array_walk:

$returnedArray = array();

function makeArray(&$element)
{
    global $returnedArray;

    $returnedArray[$element['id']]['id'] = $element['id'];
    @$returnedArray[$element['id']]['outcome'] += $element['outcome'];
    $returnedArray[$element['id']]['name'] = $element['names']['name_eng'];

}

array_walk($data, 'makeArray');

var_dump($returnedArray);


来源:https://stackoverflow.com/questions/18958628/sum-of-duplicated-values-in-nested-array-php

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