Get an unique multidimensionnal array with some values summed up?

时间:2016-07-11 20:12:35

标签: php arrays multidimensional-array sum

If I have an array like this where some values of the [0] key are repeated:

$input = array(
    array( "7", 2, 16,     46,    736),
    array( "7", 2, 16, 6.0243,  96.39),
    array( "8", 2, 16, 7.0243, 112.39),
    array( "8", 2, 16,     47,    752),
    array( "8", 2, 16, 7.0243, 112.39),
    array( "9", 0,  0, 8.0243,      0),
    array("10", 0,  0, 9.0243,      0),
    array("10", 0,  0,     49,      0),
);

What do I need to do to create a key [0] unique array where keys [2], [3] and [4] are summed when key [0] has the same value, like this:

$output = array(
    array( "7", 2, 32, 52.0243, 832.39),
    array( "8", 2, 48, 61.0486, 976.78), 
    array( "9", 0,  0,  8.0243,      0), 
    array("10", 0,  0, 58.0243,      0),
);

1 个答案:

答案 0 :(得分:1)

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][2] += $row[2];
        $new[$key][3] += $row[3];
        $new[$key][4] += $row[4];
    }
}

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