在PHP中求和数组的一部分

时间:2018-09-24 14:29:07

标签: php arrays

这完全超出了我。感谢一些帮助。 我在php中有这样的数组:

[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的总和。结果应如下所示:

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

    )

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

    )

谢谢您的帮助。

我不明白这个问题的不足。我做错了吗?无故拒绝投票没有帮助。

2 个答案:

答案 0 :(得分:1)

最简单,最有效的分组和求和方法是执行一个循环并分配临时关联密钥。

当一行被标识为新的startTime行时,保存两个所需的元素,否则将dlv_id值添加到先前存在的值。

(可选)使用no_of_subs删除临时密钥。

代码(Demo

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

答案 1 :(得分:0)

  • 使用array_column函数,我们可以使用dlv_id作为键,在两个不同的数组中分别提取no_of_subscust_id
  • 现在,只需循环遍历dlv_id的数组,如果找到匹配的键,则向其添加no_of_subs,否则(第一次设置)该值。
  • 我们使用isset函数来检查密钥是否已经存在。

尝试以下操作:

// your input array is $input_array

// get all dlv_id maintaining the cust_id as index
$dlv_id = array_column($input_array, 'dlv_id', 'cust_id');

// get all no_of_subs maintaining the cust_id as index
$no_of_subs = array_column($input_array, 'no_of_subs', 'cust_id');

$output = array();

foreach ($dlv_id as $key => $value) {

    if (isset($output[$value]['dlv_id'])) {
        $output[$value]['dlv_id'] += $no_of_subs[$key];
    } else {
        $output[$value]['dlv_id'] += $no_of_subs[$key];
    }
}