繁体   English   中英

按列值对行进行分组,并在组内创建新的总和列和计数列

[英]Group rows by column value and within groups create new sum column and count column

我试图总结一个 php 多维,我有一个这样的数组结构;

Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => Product1
            [product_price] => 0.90
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => Product2
            [product_price] => 1.50
        )

    [2] => Array
        (
            [product_id] => 1
            [product_name] => Product1
            [product_price] => 0.90
        )

)

我想写一个 function 可以很容易地总结任何重复的条目并返回一个像这样的新数组(基本上是计算 product_price 并创建一个 product_qty 字段);

Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => Product1
            [product_price] => 1.80
            [product_qty] => 2
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => Product2
            [product_price] => 1.5
            [product_qty] => 1
        )

)

我尝试过使用 array_sum()、array_merge() 和 array_map(),但没有一个返回上述期望的结果。

这是一些简单的代码:

$summary = array();
foreach ($products as $product) {
    if (!isset($summary[$product['product_id']])) {
        $summary[$product['product_id']] = array_merge(
            $product, array('product_qty' => 1));
    } else {
        $summary[$product['product_id']]['product_price'] += $product['product_price'];
        $summary[$product['product_id']]['product_qty']++;
    }
}

暂无
暂无

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

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