Search code examples
phparraysmultidimensional-arraygroup-bysum

Group 2d data by one column and sum another column to produce associative array


I need to group data from my 2d array by one column and sum another column value in the respective groups.

In my data, commas are used as the decimal place character -- these are float values.

Input:

[
    [18, '1,07'];
    [ 8, '0,44'],
    [ 8, '0,67'],
    [18, '0,55'],
    [18, '0,19'],
    [ 8, '0,48'],
    [18, '2,59'],
    [ 8, '0,15'],
    [18, '12,97'],
]

Desired result:

[
    18 => '17,37',
     8 =>  '1,74',
]

Solution

  • Try something like this:

    <?php
    
    $data = Array ( 
        Array ( 0 => '18', 1 => '1,07' ),
        Array ( 0 => '8', 1 => '0,44' ),
        Array ( 0 => '8', 1 => '0,67' ),
        Array ( 0 => '18', 1 => '0,55' ), 
        Array ( 0 => '18', 1 => '0,19' ),
        Array ( 0 => '8', 1 => '0,48' ),
        Array ( 0 => '18', 1 => '2,59' ),
        Array ( 0 => '8', 1 => '0,15' ),
        Array ( 0 => '18', 1 => '12,97' ) 
    );
    
    // predefine array
    $data_summ = array();
    foreach ( $data as $value ) {
        $data_summ[ $value[0] ] = 0;
    }
    
    foreach ( $data as $list ) {
        $number = str_replace( ",", ".", $list[1] ) * 1;
        $data_summ[ $list[0] ] += (float)$number;
    }
    
    ?>
    

    Output of $data_summ:

    Array
    (
        [8] => 1.74
        [18] => 17.37
    )
    

    If I understand you correctly.