在 php 中对数组的部分求和 [英] Sum parts of an array in php

查看:64
本文介绍了在 php 中对数组的部分求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这完全超出我的范围.感谢一些帮助.我在 php 中有一个数组,如下所示:

this is quite beyond me. Appreciate some help. I have an array in php like so:

[0] => Array
    (
        [cust_id] => 1006
        [no_of_subs] => 2
        [dlv_id] => 1000
    )

[1] => Array
    (
        [cust_id] => 1011
        [no_of_subs] => 3
        [dlv_id] => 1000
    )

[2] => Array
    (
        [cust_id] => 1012
        [no_of_subs] => 5
        [dlv_id] => 1001
    )

[3] => Array
    (
        [cust_id] => 1013
        [no_of_subs] => 6
        [dlv_id] => 1001
    )

我不需要 cust_id 字段.我只需要为每个匹配的 dlv_id 对 dlv_id 和 no_of_subs 的总和进行分组.结果应该是这样的:

I don't need the cust_id field. I just need to group the dlv_id and the sum of no_of_subs for each matching dlv_id. The result should look like this:

[0] => Array
    (
        [dlv_id] => 1000
        [no_of_subs] => 5

    )

[1] => Array
    (
        [cust_id] => 1011
        [no_of_subs] => 11

    )

感谢您的帮助.

我不明白这个问题的反对票.我做错了吗?无缘无故地拒绝投票无济于事.

I don't understand the downvotes for this question. Am i doing it all wrong? Downvoting without a reason is not helping.

推荐答案

最简单、最有效的分组和求和方法是执行单个循环并分配临时关联键.

The simplest, most efficient way to group and sum is to perform a single loop and assign temporary associative keys.

当一行被识别为新的 dlv_id 行时,保存两个所需的元素,否则将 no_of_subs 值添加到预先存在的值中.

When a row is identified as a new dlv_id row, save the two desired elements, otherwise add the no_of_subs value to the pre-existing value.

或者,使用 array_values() 删除临时键.

Optionally, remove the temporary keys with array_values().

代码(演示)

$array = [
    ["cust_id" => 1006, "no_of_subs" => 2, "dlv_id" => 1000],
    ["cust_id" => 1011, "no_of_subs" => 3, "dlv_id" => 1000],
    ["cust_id" => 1012, "no_of_subs" => 5, "dlv_id" => 1001],
    ["cust_id" => 1013, "no_of_subs" => 6, "dlv_id" => 1001]
];

foreach ($array as $row) {
    if (!isset($result[$row["dlv_id"]])) {
        $result[$row["dlv_id"]] = ["dlv_id" => $row["dlv_id"], "no_of_subs" => $row["no_of_subs"]];
    } else {
        $result[$row["dlv_id"]]["no_of_subs"] += $row["no_of_subs"];
    }
}
var_export(array_values($result));

输出:

array (
  0 => 
  array (
    'dlv_id' => 1000,
    'no_of_subs' => 5,
  ),
  1 => 
  array (
    'dlv_id' => 1001,
    'no_of_subs' => 11,
  ),
)

这篇关于在 php 中对数组的部分求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆