How to identify elements with repeated values in an array and create a new array

0

I have the following associative array:

Current Array:

Array
(
[0] => Array
    (
        [num] => 51
        [totalparcial] => 2.50
    )

[1] => Array
    (
        [num] => 51
        [totalparcial] => 3.70
    )

[2] => Array
    (
        [num] => 52
        [totalparcial] => 5.00
    )

[3] => Array
    (
        [num] => 52
        [totalparcial] => 22.00
    )

[4] => Array
    (
        [num] => 52
        [totalparcial] => 14.00
    )

)

How can I get index information that has the same value in [num] , add [totalparcial] , and create a new array with these new values?

In this example I would like the final result to be an array like this:

Array Desired:

Array
(
[0] => Array
    (
        [num] => 51
        [totalparcial] => 6.20
    )

[1] => Array
    (
        [num] => 52
        [totalparcial] => 41.00
    )
)

Thanks!

    
asked by anonymous 18.05.2017 / 03:57

1 answer

1

You can use:

$resultado = array();
foreach($array as $a){
    if(isset($resultado[$a['num']]))
         $resultado[$a['num']]['totalparcial'] += $a['totalparcial'];
    else
         $resultado[$a['num']] = $a;
}

If you need the sequence array keys that are not equal to 'num', add:

$resultadoSequencial = array();
foreach($resultado as $r)
      $resultadoSequencial[] = $r;
    
18.05.2017 / 10:23