[英]PHP array reorganize with unique count
我有以下数组,其中 ID 作为索引,有些作为值。 最终目标是获得另一个数组中唯一 ID 的总数。
Array ( [0] => Array ( [0] => Team Object ( [id] => 1 [countStat] => 25 ) ) [1] => Array ( [0] => Team Object ( [id] => 2 [countStat] => 24 ) ) [2] => Array ( [0] => Team Object ( [id] => 1 [countStat] => 23 ) ) [3] => Array ( [0] => Team Object ( [id] => 3 [countStat] => 23 ) ) [4] => Array ( [0] => Team Object ( [id] => 5 [countStat] => 21 ) ) [5] => Array ( [0] => Team Object ( [id] => 3 [countStat] => 21 ) ) [6] => Array ( [0] => Team Object ( [id] => 5 [countStat] => 20 ) ) [7] => Array ( [0] => Team Object ( [id] => 2 [countStat] => 20 ) ) )
我想要如下结果。
Array ( [0] => Array ( [0] => Team Object ( [id] => 1 [countStat] => 48 ) ) [1] => Array ( [0] => Team Object ( [id] => 2 [countStat] => 44 ) ) [3] => Array ( [0] => Team Object ( [id] => 3 [countStat] => 44 ) ) [4] => Array ( [0] => Team Object ( [id] => 5 [countStat] => 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
)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.