繁体   English   中英

获取一个唯一的多维数组,其中包含一些值的总和?

[英]Get an unique multidimensionnal array with some values summed up?

如果我有一个这样的数组,其中重复[0]键的一些值:

$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),
);

我需要做什么来创建键[0]唯一的数组,当键[0]具有相同的值时,将键[2][3][4]相加,如下所示:

$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),
);

看来您正在尝试在PHP中实现数据库聚合功能 尝试执行此类操作时,其基本概念是将希望分组的一个或多个值用作结果数组中的键。 因此,如下遍历您的行集:

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];
    }
}

当然,如果您正在使用的数据实际上来自数据库,那么在选择查询中进行分组和求和比在PHP中进行处理最有可能会更好:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM