php - PHP数组用唯一计数重组
问题描述
我有以下数组,其中 ID 作为索引,有些算作值。最终目标是在另一个数组中获得唯一 ID 的总数。
大批 ( [0] => 数组 ( [0] => 团队对象 ( [id] => 1 [计数统计] => 25 ) ) [1] => 数组 ( [0] => 团队对象 ( [id] => 2 [计数统计] => 24 ) ) [2] => 数组 ( [0] => 团队对象 ( [id] => 1 [计数统计] => 23 ) ) [3] => 数组 ( [0] => 团队对象 ( [id] => 3 [计数统计] => 23 ) ) [4] => 数组 ( [0] => 团队对象 ( [id] => 5 [计数统计] => 21 ) ) [5] => 数组 ( [0] => 团队对象 ( [id] => 3 [计数统计] => 21 ) ) [6] => 数组 ( [0] => 团队对象 ( [id] => 5 [计数统计] => 20 ) ) [7] => 数组 ( [0] => 团队对象 ( [id] => 2 [计数统计] => 20 ) ) )
我想要如下结果。
大批 ( [0] => 数组 ( [0] => 团队对象 ( [id] => 1 [计数统计] => 48 ) ) [1] => 数组 ( [0] => 团队对象 ( [id] => 2 [计数统计] => 44 ) ) [3] => 数组 ( [0] => 团队对象 ( [id] => 3 [计数统计] => 44 ) ) [4] => 数组 ( [0] => 团队对象 ( [id] => 5 [计数统计] => 41 ) ) )
我花了几个小时研究它,但无法得到解决方案。有人可以帮忙吗?
谢谢你。
解决方案
看起来您想对类似 id 的团队对象的 countStats 求和。我创建了一个类似的数据结构,通过它循环形成一个临时数组,该数组使用 id 作为键,以及相关的金额(稍后求和 - 我的是金额,你的是 countStats)。然后将这些相加并重新创建所需的输出。
<?php
class Team
{
public $id;
public $amount;
public function __construct($id, $amount)
{
$this->id = $id;
$this->amount = $amount;
}
}
$input =
[
[new Team(1, 3)],
[new Team(1, 4)],
[new Team(2, 5)],
[new Team(2, 7)]
];
foreach($input as $subarray)
$amounts[$subarray[0]->id][]=$subarray[0]->amount;
print_r($amounts);
foreach($amounts as $k => $v)
$result[] = [new Team($k, array_sum($v))];
print_r($result);
输出:
Array
(
[1] => Array
(
[0] => 3
[1] => 4
)
[2] => Array
(
[0] => 5
[1] => 7
)
)
Array
(
[0] => Array
(
[0] => Team Object
(
[id] => 1
[amount] => 7
)
)
[1] => Array
(
[0] => Team Object
(
[id] => 2
[amount] => 12
)
)
)
推荐阅读
- websocket - 客户端在 apache 上断开连接并请求数据后,服务器正在自行发起 GET 请求
- jquery - Rails 6:link_to 方法::delete 不起作用
- r - 如何对 R 中每个唯一组的值求和
- webassembly - WebAssembly 使用 i64 作为分支条件
- html - 如何调整 Ngx-Gallery 预览图像宽度?
- javascript - 比较数组中的关键字值字段 - Javascript
- gitlab - gitlab CI/CD:如何仅触发特定作业
- html - 按下按钮时调用功能 - 反应
- python - Python设置无法执行python脚本
- google-apps-script - 我想将内容从一个电子表格转移到另一个电子表格(电子表格 A 到电子表格 B),并手动将记录输入到 B