user1719210 user1719210 - 4 months ago 7
PHP Question

Get an unique multidimensionnal array with some values summed up?

What is the best way to get this result :

My input array

Array{
array { [0]=> string(1) "7" [1]=> int(2) [2]=> float(16) [3]=> float(46) [4]=> float(736)}
array { [0]=> string(1) "7" [1]=> int(2) [2]=> float(16) [3]=> float(6.0243) [4]=> float(96.39)}

array { [0]=> string(1) "8" [1]=> int(2) [2]=> float(16) [3]=> float(7.0243) [4]=> float(112.39)}
array { [0]=> string(1) "8" [1]=> int(2) [2]=> float(16) [3]=> float(47) [4]=> float(752)}
array { [0]=> string(1) "8" [1]=> int(2) [2]=> float(16) [3]=> float(7.0243) [4]=> float(112.39)}

array { [0]=> string(1) "9" [1]=> int(0) [2]=> float(0) [3]=> float(8.0243) [4]=> float(0)}

array { [0]=> string(2) "10" [1]=> int(0) [2]=> float(0) [3]=> float(9.0243) [4]=> float(0)}
array { [0]=> string(2) "10" [1]=> int(0) [2]=> float(0) [3]=> float(49) [4]=> float(0)}
}


Desired result :

array{
array { [0]=> string(1) "7" [1]=> int(2) [2]=> float(32) [3]=> float(52.0243) [4]=> float(832.39)}
array { [0]=> string(1) "8" [1]=> int(2) [2]=> float(48) [3]=> float(61.0486) [4]=> float(112.39)}
array { [0]=> string(1) "9" [1]=> int(0) [2]=> float(0) [3]=> float(8.0243) [4]=> float(0)}
array { [0]=> string(2) "10" [1]=> int(0) [2]=> float(0) [3]=> float(58.0243) [4]=> float(0)}
}


A key[0] unique array where keys[2],[3] and [4] are summed when key[0] has the same value.

Thank you a lot in advance !

Answer

It looks like you are trying to implement a database aggregate function in PHP. The underlying concept when trying to do something like this is to use the value (or values) that you wish to group by as the key in your result array. So loop over your set of rows as follows:

foreach ($original as $row) {

    $key = $row[0];                // use the column you want to group by as the key

    if (!isset($new[$key])) {
        $new[$key] = $row;         // for new instances of the key, just add the whole row
    } else {

        // if the key has already been set, add to the non-key columns to accumulate the sum

        $new[$key][3] += $row[3];
        $new[$key][4] += $row[4];
        $new[$key][5] += $row[5];
    }
}

Of course, if the data you're working with actually comes from a database, it will most likely be better to do the grouping and sums in your select query rather than doing it in PHP:

SELECT col1, MAX(col2), SUM(col3), SUM(col4), SUM(col5) FROM your_table GROUP BY col1
Comments