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

Asked

Viewed 313 times

0

I have the following associative array:

Array Actual:

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 information from the index that has the same value in [num] , add the [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!

1 answer

1


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 sequential array keys not equal to num, add:

$resultadoSequencial = array();
foreach($resultado as $r)
      $resultadoSequencial[] = $r;
  • Generated the array exactly as I needed! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.