概述
这超出了我的范围.感谢一些帮助.
我在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
)
感谢您的任何帮助.
我不明白这个问题的downvotes.我做错了吗?没有理由的贬低是无济于事的.
解决方法:
分组和求和的最简单,最有效的方法是执行单个循环并分配临时关联键.
将行标识为新的dlv_id行时,保存两个所需的元素,否则将no_of_subs值添加到预先存在的值.
(可选)使用array_values()删除临时密钥.
代码(Demo)
$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,arrays
来源: https://codeday.me/bug/20191003/1850480.html
最后
以上就是包容野狼为你收集整理的php对数组某一字段求和_在PHP中对数组的部分求和的全部内容,希望文章能够帮你解决php对数组某一字段求和_在PHP中对数组的部分求和所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复