Group arrays with equal fields

2

Personal wave I have the following representation of an array

    [cfop] => Array
        (
            [0] => Array
                (
                    [code] => 1403
                    [value] => 10.50
                )

            [1] => Array
                (
                    [code] => 1403
                    [value] => 1.50
                )
            [2] => Array
                (
                    [code] => 2102
                    [value] => 27.60
                )

        )

I would like with (PHP) to group and sum the values of the "value" fields where the "code" field is equal, the final representation would look like this

        [cfop] => Array
            (
                [0] => Array
                    (
                        [code] => 1403
                        [value] => 12.00
                    )
                [1] => Array
                    (
                        [code] => 2102
                        [value] => 27.60
                    )

            )

I tried this

            if($event['cfop']){

                $cfops       = [];

                foreach($event['cfop'] as $item){

                    $exist = false;

                    foreach($cfops as &$cfop){

                        if($item['code'] == $cfop['code']){

                            $exist = true;

                            $cfop['value'] += $item['value'];

                        }
                    }

                    if(!$exist) $cfops[] = $item;
                }

                $event['cfop'] = $cfops;

                unset($cfops); 
            }

But it did not work, it ends up duplicating some aray items

    
asked by anonymous 27.12.2018 / 16:24

0 answers